Home Short writing in Matlab for getting the minimum of two vectors at each position
Reply: 1

Short writing in Matlab for getting the minimum of two vectors at each position

Kev1n91
1#
Kev1n91 Published in 2017-12-07 12:33:08Z

I have the following code:

for i=1:length(Z1)
    if Z1(i) < Z2(i)
        min_vec(i) = Z1(i)
    else
        min_vec(i) = Z2(i)
    end
end

I am wondering if there is a more "matlab" short writing way to achieve the same goal?

il_raffa
2#
il_raffa Reply to 2017-12-07 12:54:13Z

You can use min function:

If you are only interest only to the minimum value, you can simply use Z1 and Z2 as input:

min_Z1_Z2=min(Z1,Z2)

if you are also interested to know in which of the two array the minimun value is, you can call min with two parameters as output and passing as input the two array as a matrix

[min_val,Z1_Z2]=min([Z1;Z2])

In min_val you have the minimum value, in Z1_Z2 the values 1 or 2 according if the min value is in the first or the second row, that is Z1 or Z2

Z1=randi([1 33],1,10)
Z2=randi([1 33],1,10)
min_Z1_Z2=min(Z1,Z2)
[min_val,Z1_Z2]=min([Z1;Z2])


>> Z1
Z1 =

   24   12   16   21   22   15   28    7   17   29

>> Z2
Z2 =

   27   26   23    2    5   10   25   23   29    9

>> min_val
min_val =

   24   12   16    2    5   10   25    7   17    9

>> Z1_Z2
Z1_Z2 =

   1   1   1   2   2   2   2   1   1   2

Hope this helps,

Qapla'

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.408977 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO