How to use values of certain matrices without using for loop?
2 views (last 30 days)
Show older comments
Beibit Sautbek
on 2 Aug 2016
Commented: Star Strider
on 2 Aug 2016
I have certain values a, b and c. I have P=a*b/c;
For example, If a=2, b=6, c=4. Then P will be P=2*6/4=3;
But, If I want to check three cases, when values of a, b and c will change, how P will be changed?
First case:: If I want to check effect of 'a',
If a=(1:1:10); b=6, c=4. So, in this case P will be matrix .
Second case:: If I want to check effect of 'c',
If a=2; b=6, c=(100:100:1000). So, in this case P will be matrix .
How Can I do this, without using for loop and 'if'?
Could anyone help me?
P.S. I have large code, and a lot of values as a, b and c. Therefore will be very complicated to use for loop and if.
0 Comments
Accepted Answer
Star Strider
on 2 Aug 2016
You need to vectorize the expression. The easiest way to do what you want is to turn ‘P’ into an anonymous function and if all your values are between 1 and 10, use a meshgrid call:
P = @(a,b,c) a.*b./c;
[M1,M2,M3] = meshgrid(1:10);
Pm = P(M1,M2,M3);
This runs. I do not know what you want, so I will leave you to sort out the ‘Pm’ matrix.
2 Comments
Star Strider
on 2 Aug 2016
Change the meshgrid call:
a_range = [a1, a2];
b_range = [b1, b2];
c_range = [c1, c2];
av = linspace(min(a_range), max(a_range), 10);
bv = linspace(min(b_range), max(b_range), 10);
cv = linspace(min(c_range), max(c_range), 10);
[M1,M2,M3] = meshgrid(av, bv, cv);
Change the number of vector elements (here 10) in each vector if necessary.
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!