Make matrix with loop

3 views (last 30 days)
Pham Anh
Pham Anh on 27 May 2020
Commented: Walter Roberson on 27 May 2020
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?

Answers (1)

Walter Roberson
Walter Roberson on 27 May 2020
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 Comments
Pham Anh
Pham Anh on 27 May 2020
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 on 27 May 2020
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

Sign in to comment.

Categories

Find more on Language Fundamentals in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!