How can I return the values of a loop

39 views (last 30 days)
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

Accepted Answer

Felix Lauwaert
Felix Lauwaert on 12 May 2016
Edited: Felix Lauwaert on 12 May 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;
  1 Comment
zaxtronix on 13 May 2016
Thanks a lot man, how did you do it using this numel function, I definitely wouldn't have been able to come about it.

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 12 May 2016
Edited: Andrei Bobrov on 12 May 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;
Andrei Bobrov
Andrei Bobrov on 13 May 2016
[ii,jj] = ndgrid(1:5,0:5);
k = ii.^2 + ii.*jj + jj.^2;

Sign in to comment.


Find more on Loops and Conditional Statements 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!