How can I return the values of a loop
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
zaxtronix
am 12 Mai 2016
Kommentiert: Andrei Bobrov
am 13 Mai 2016
I want to return the entire values of k matrice but I only end up with values from the last row.
for i = 1:5,
j = 0:i;
k = i.^2 + i*j + j.^2
end
0 Kommentare
Akzeptierte Antwort
Felix Lauwaert
am 12 Mai 2016
Bearbeitet: Felix Lauwaert
am 12 Mai 2016
You are computing k once for each value of i and overwriting it. If I understand what you want, try:
i = 1:5;
j = 0:5;
k = zeros(numel(i),numel(j));
for a = 1:numel(i)
for b = 1:numel(j)
k(a,b) = i(a)^2 + i(a)*j(b) + j(b)^2;
end
end
display(k)
Weitere Antworten (1)
Andrei Bobrov
am 12 Mai 2016
Bearbeitet: Andrei Bobrov
am 12 Mai 2016
n = 5;
k = tril(((1:n)'*ones(1,n+1)).^2+(1:n)'*(0:n)+(ones(n,1)*(0:n)).^2,1);
with for..end loop
n = 5;
k = zeros(n,n+1);
for ii = 1:5,
jj = 0:ii;
k(ii,1:ii+1) = ii.^2 + ii*jj + jj.^2;
end
2 Kommentare
Andrei Bobrov
am 13 Mai 2016
hm...
[ii,jj] = ndgrid(1:5,0:5);
k = ii.^2 + ii.*jj + jj.^2;
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements 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!