Make matrix with loop
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Walter Roberson
am 27 Mai 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 Kommentare
Walter Roberson
am 27 Mai 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
Siehe auch
Kategorien
Mehr zu Language Fundamentals finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!