for loop with vectors of different dimensions help
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
soloby
am 23 Jun. 2015
Kommentiert: Walter Roberson
am 23 Jun. 2015
x = -10:0.1:10;
y = 0:.005:1;
f1 = trapmf(x,[-2 0 0 2]);
f2 = trapmf(x,[3 6 6 9]);
for i = 1:201
y(i) = [x(i),f1(i)]
end
this doesn't seem to work but I dont know why??
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 23 Jun. 2015
x = -10:0.1:10;
f1 = trapmf(x,[-2 0 0 2]);
f2 = trapmf(x,[3 6 6 9]);
y = [x(:), f1(:)];
this would produce two columns; you could also use rows like
y = [x; f1];
If you need to use a loop then
x = -10:0.1:10;
f1 = trapmf(x,[-2 0 0 2]);
f2 = trapmf(x,[3 6 6 9]);
y = zeros(length(x), 2);
for k = 1 : length(x)
y(k,:) = [x(k), f1(k)];
end
5 Kommentare
Walter Roberson
am 23 Jun. 2015
y(k,:) means to take the k'th row (e.g., k=3 would be row #3), and all columns. So all of row #k.
Weitere Antworten (1)
Geoff Hayes
am 23 Jun. 2015
Soloby - please clarify what you mean by this doesn't seem to work. What is the problem? Are you observing any errors, and if so, what are they? Could it be that the error is In an assignment A(I) = B, the number of elements in B and I must be the same.
Note that you initialize y to be an array of 201 elements and then overwrite each element of y in the for loop. Why? Are you trying to populate y so that it is a 201x1 array. If so, it may be that you want to be doing the following instead
for k = 1:201
y(k,:) = [x(k),f1(k)];
end
Note the use of k as the index variable rather than i since MATLAB uses the latter to represent the imaginary number.
2 Kommentare
Walter Roberson
am 23 Jun. 2015
It would depend how you initialized y. In your initial code you initialized y as a row vector, so it would be 1 x 201, so when k was 1 you would be trying to assign a two element vector into y(1,:) which is 1 x 141. You need to either not initialize y or initialize y to 141 x 2 like I did in my version.
Siehe auch
Kategorien
Mehr zu Debugging and Analysis finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!