Why is this for loop not producing unique values for each index of the calculated matrix?

2 views (last 30 days)
This is the part of the script I am having trouble with:
load('DENS.mat')
for i = 1:151
Vsto(i) = sqrt(2*2800/(DENS(i)*180*1.7));
Vlof(i) = 1.15*Vsto(i);
Vavg(i) = sqrt((Vlof(i))^2/2);
Davg(i) = 0.5*DENS(i)*Vavg(i)^2*(180)*(0.0870);
end
The DENS matrix is a 1x151 double which I have attached to this post. I want to produce a 1x151 matrix called Davg with values corresponding to Vavg and DENS. The problem is that when I run this part of my script I get a 1x151 matrix with 151 values which are the same and correspond to DENS(151) and Vavg(151) for every value within Davg. If you remove the square (the ^2 beside Vavg(i)), however, this problem goes away and I get 151 unique, but wrong, values within Davg. The other matrices Vsto, Vlof, and Vavg produce correct values.
What is wrong with this code? I think it has something to do with the square in Davg and the sqrt function in Vavg but I don't know how.
Thank you

Accepted Answer

Jan
Jan on 7 May 2018
Edited: Jan on 7 May 2018
Why do you assume, that the output is wrong? Numerically it is correct and Matlab calculates exactly what it is instructed to do.
A simplified version of the code:
load('DENS.mat')
for i = 1:151
Vsto(i) = sqrt(2 * 2800 / (DENS(i) * 180 * 1.7));
Vlof(i) = 1.15 * Vsto(i);
Vavg(i) = sqrt(Vlof(i) ^ 2 / 2);
Davg(i) = 0.5 * DENS(i)*Vavg(i)^2 * 180 * 0.0870;
end
Now vectorize this instead of the loop:
Vsto = sqrt(2 * 2800 ./ (DENS * 180 * 1.7));
Vlof = 1.15 * Vsto;
Vavg = abs(Vlof) / sqrt(2); % Cheaper than: sqrt(Vlof(i) ^ 2 / 2)
Davg = 0.5 * DENS .* Vavg .^ 2 * 180 * 0.0870;
These terms can be combined:
Davg = 0.5 * DENS .* ...
(abs(1.15 * sqrt(5600 ./ (DENS * 180 * 1.7))) / sqrt(2)) .^ 2 * ...
180 * 0.0870
Then DENS ./ (sqrt(DENS) .^ 2) removes the dependency to the input and you get a constant. To be exact:
Davg = repmat(0.25 * 180 * 0.0870 * 1.3225 * 5600 / (180 * 1.7), size(DENS))

More Answers (2)

Image Analyst
Image Analyst on 7 May 2018
If you just plug each term into the following one, you'll see that DENS completely cancels out and all you're left with is the constants, hence Davg is a constant.

Bob Thompson
Bob Thompson on 7 May 2018
After expanding and simplifying your equations I can safely say that when Vavg^2 is used then Davg(i) = 94.753... because you are effectively taking DENS(i)/DENS(i) multiplied by a series of constants which end up being 94.753. Double check your equations.

Tags

Community Treasure Hunt

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

Start Hunting!