How can i correct the subscript of a vector in a for loop ?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Mallouli Marwa
am 7 Okt. 2016
Kommentiert: Walter Roberson
am 10 Okt. 2016
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 Kommentare
Akzeptierte Antwort
Marc Jakobi
am 7 Okt. 2016
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 Kommentare
Marc Jakobi
am 9 Okt. 2016
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?)
Weitere Antworten (1)
Walter Roberson
am 9 Okt. 2016
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 Kommentare
Walter Roberson
am 10 Okt. 2016
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.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!