for loop with vectors of different dimensions help
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2015-6-23
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 个评论
Walter Roberson
2015-6-23
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.
更多回答(1 个)
Geoff Hayes
2015-6-23
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 个评论
Walter Roberson
2015-6-23
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Performance 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!