Make matrix with loop
2 次查看(过去 30 天)
显示 更早的评论
hi i'm new I am executing the loop using FOR. Each loop I get 1 number. I want to put those numbers in a matrix.
Can anyone help me?
0 个评论
回答(1 个)
Walter Roberson
2020-5-27
In the general case:
xvals = [list of x values, does not have to be regularly spaced or even sorted];
numx = length(xvals);
y = zeros(1,numx); %pre-allocate
for xidx = 1 : numx
x = xvals(xidx);
thisy = some calculation involving x
y(xidx) = thisy;
end
In the special case where x is integers increasing by 1, but not necessarily starting from 1:
firstx = value
lastx = value
numx = lastx - firstx + 1;
y = zeros(1, numx); %pre-allocate
for x = firstx : lastx
thisy = some calculation involving x
y(x - firstx + 1) = thisy;
end
In the special case where x is integers starting from 1 and increasing by 1:
y = zeros(1, lastx); %pre-allocate
for x = 1 : lastx
thisy = some calculation involving x
y(x) = thisy;
end
It would be common that the expression is simple enough that it is clear to put the body into one line:
y = zeros(1, lastx); %pre-allocate
for x = 1 : lastx
y(x) = some calculation involving x
end
pre-allocation is not strictly necessary, but it can make a fairly noticable difference in performance.
2 个评论
Walter Roberson
2020-5-27
function test(A)
Ax=A(:,1);
x = zeros(size(Ax,1),1);
for i=1:size(Ax,1)
x(i) = Ax(i)*2+7
end
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!