How can i correct the subscript of a vector in a for loop ?
2 ビュー (過去 30 日間)
古いコメントを表示
Hi
I want to plot X=f(wr) but i have this error
Subscript indices must either be real positive integers or logicals.
Knowing that mr,damping,kr are matrix(40*40)
And my program is :
Damping=(2*zeta*kr)/(6600*pi);
F=[zeros(39,1);ones(1,1)];
IIw=linspace(5,10,40);
wr=IIw*2*pi;
for w=wr(1):wr(40)
X(w)=(-w.^2*mr + j*w*Damping + kr)\ F;
end
plot(wr,abs(X))
0 件のコメント
採用された回答
Marc Jakobi
2016 年 10 月 7 日
Your problem is that you are inxexing X with w, which may be a decimal.
To correct it, use:
ind = 0;
for w=wr(1):wr(40)
ind = ind+1;
X(ind)=(-w.^2*mr + j*w*Damping + kr)\ F; %%you were indexing X(w)
end
4 件のコメント
Marc Jakobi
2016 年 10 月 9 日
w is not a vector.
since
IIw=linspace(5,10,40);
wr=IIw*2*pi;
wr is a 1x40 vector. and
for w = wr(1):wr(40)
w is always a scalar. Maybe it would be easier to help you if you tell us what problem you are trying to solve. And what would you like to plot? (Just one single line or more than one?)
その他の回答 (1 件)
Walter Roberson
2016 年 10 月 9 日
In your code
(-w.^2*mr + j*w*Damping + kr)\ F
your matrices in () are 40 x 40, and your F is 40 x 1. The \ operator requires that the number of rows match on the left and right (which it does in this case, both have 40 rows), and it will return a column vector with as many entries as there are columns on the left. You have 40 columns on the left so you get a column vector of length 40. And then you try to store that into the single location X(w) or X(ind) .
I suggest
num_w = length(wr);
X = zeros(size(mr,2), num_w);
for ind = 1 : num_w
w = wr(ind);
X(:, ind) = (-w.^2*mr + j*w*Damping + kr)\ F;
end
plot(wr, abs(X))
Note: along the way I corrected your code to loop over all of the values present in wr. Your code was not doing that: it was doing
for w = [wr(1), wr(1)+1, wr(1)+2, wr(1)+3, ... wr(40)]
which is to say, it was taking values 1 apart starting from wr(1) until wr(40).
The notation wr(1):wr(40) does not mean "all the values in wr from index 1 to 40", it means the same as wr(1):1:wr(40) which is taking values separated by 1 starting from wr(1) and ending no greater than wr(40)
for w = wr
would use all of the values in wr, but it would not be in a form suitable for using as an index into the output array.
2 件のコメント
Walter Roberson
2016 年 10 月 10 日
My suggested changes do obtain the value of X for each value of wr. The values are stored in columns of X, with column K of X corresponding to the K'th value in wr.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!