Make matrix with loop

조회 수: 1 (최근 30일)
Pham Anh
Pham Anh 2020년 5월 27일
댓글: Walter Roberson 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에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by