How can I use for loop to generate the data.

1 view (last 30 days)
I am trying to generate data using for loop. I have included all of the data below:
p1 is the values or array that will be varied, and fun equation and result will give different values. Also, p4 is fixed.
I sort of know that
for 1:length(p1) ...
end ...
but, I am not sure..
p1 = [6.78,2.79,9.8,11.93,7.81,8.83,5.81,12.85,10.94,7.84,5.29,4.83,9.77];
p4 = 29.85;
fun = @(p2) p2/p4*(1 -((gamma-1)*(p2/p1-1))./(2*gamma*(2*gamma+(gamma+1)*(p2/p1-1))).^.5).^(-2.*gamma./(gamma-1))-1;
result = fzero(fun,10)/p1;
end
  6 Comments
Walter Roberson
Walter Roberson on 8 Mar 2020
Ameer, that will not work.
p1 is a row vector.
fzero passes scalars into the function, so inside fun, p2 will be a scalar.
p2/p1 is then scalar / row vector . That will give you an error about incompatible dimensions. At the very least you need to change the p2/p1 to p2./p1 in all places
However, p2./p1 will give a vector result, so the value of fun would be a vector. fzero() can never find the zero of a vector: fzero() is restricted to processing functions that produce scalars.
fsolve() can handle vectors of values, but when you pass the scalar 10 as the initial guess, that would tell fsolve() to find a single scalar value that makes all of the expressions 0, which is not something that can be done. So you would have to change the initial guess of 10 into 10*ones(size(p1)) . But that be inefficient as it would try to adjust the entries of a vector of length 13 against each other to try to reduce the calculation error, which is something that doesn't need to be done as we know the expressions are independent.
In other posts by the same user, I show how to use arrayfun() to deal with this situation more efficiently.
Ameer Hamza
Ameer Hamza on 8 Mar 2020
Walter, correct. Thanks for pointing out. I overlooked this issue.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!