Looping over a vector with non-integer values

I'm trying to loop through each element of the vector 'N' but it keeps giving me back the 'attempting to access; index must be a positive integer or logical.' Is there a way I can do this without having to do each of them separately?
N = [15.66 9.27 6.72 4.84 4.1 3.4];
km_factors = zeros(size(N));
r = (616/2)/1000;
m = 1140;
vh = 1.999;
for i = N
x(i) = (0.3*i)/r;
z = m/vh;
km_factors = (2.73e-02*(x(i)))+(9.85e-04*(x(i)^2))-(5.71e-05*(z)) ...
+(8.22e-08*(z^2))-(2.87e-05*(x(i)*z));
end
disp(km_factors);

2 件のコメント

per isakson
per isakson 2015 年 2 月 4 日
"do each of them separately?" &nbsp What do you mean? Do what separately?
Levi Autrey
Levi Autrey 2015 年 2 月 4 日
I guess I should have worded that a little better. I mean loop through each individual number in 'N' 'by hand', if you will.

サインインしてコメントする。

 採用された回答

Star Strider
Star Strider 2015 年 2 月 4 日

0 投票

I don’t know exactly what you want, but one solution is to set the for loop index to go from 1 to the length of ‘N’. I substituted ‘N(i)’ for ‘i’ in the ‘x’ assignment, and subscripted ‘km_factors’. It works. Check to be certain it calculates what you want:
N = [15.66 9.27 6.72 4.84 4.1 3.4];
km_factors = zeros(size(N));
r = (616/2)/1000;
m = 1140;
vh = 1.999;
for i = 1:length(N)
x(i) = (0.3*N(i))/r;
z = m/vh;
km_factors(i) = (2.73e-02*(x(i)))+(9.85e-04*(x(i)^2))-(5.71e-05*(z))+(8.22e-08*(z^2))-(2.87e-05*(x(i)*z));
end
Note that it’s generally not a good idea to use ‘i’ and ‘j’ as variables, including loop counters, because MATLAB uses those for its imaginary operators. Not using them as variables avoids confusion.

2 件のコメント

Levi Autrey
Levi Autrey 2015 年 2 月 4 日
It works. Thank you very much, I've been struggling with this for quite some time.
Star Strider
Star Strider 2015 年 2 月 4 日
My pleasure!
I remember encountering the same problem when I was learning MATLAB.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by