Make matrix with loop

2 次查看(过去 30 天)
Pham Anh
Pham Anh 2020-5-27
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?

回答(1 个)

Walter Roberson
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 个评论
Pham Anh
Pham Anh 2020-5-27
i has a 25x2 matrix
i using this function to loop
function test(A)
Ax=A(:,1);
for i=1:size(Ax,1)
x = Ax(i)*2+7
end
i dont know how to list the x values
My purpose is to create a 25x1 matrix from x
Walter Roberson
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Language Fundamentals 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by