MATLAB Answers

manoj saini

how will use nested loop

hello my problem is that i have 11 value for any variable suppose i=1:11 and have another variable suppose b=2:12 also has 11 values now my question is that i want to find out value for i=1 for z=i*b total 11 values and for i=2 another 11 value of z and so on how i can use nested loop


It's not clear what you want. Please give an example with 2 11-element arrays, a and b, and what output(s) you want.

for i=1 I want 11 values of i*b in one row for i=2 I want 11 values of i*b in one row for i=3 I want 11 values of i*b in one row AND SO ON..............

Yes, and all of the Answers so far give you that.


No products are associated with this question.

4 Answers

Answer by Muruganandham Subramanian on 19 Dec 2012
Edited by Muruganandham Subramanian on 19 Dec 2012
 Accepted answer

try this:

z = zeros(11,11); 
for a=1:11 
  for b=2:12    


You declare z as 11 x 11, but then you use it as 11 x 12.

Because of the way MATLAB handles assignments to non-existant locations, this will work, but it does indicate a logic fault on your part.

@walter..I agre your point..

Answer by Babak
on 18 Dec 2012

 Z = zeors(11,11);
 for i=1:11 
  for b=2:12 


thanks this shows right answer

sir now if my varible i=0.1:.11 and b also in point then how it will save

If the number you're multiplying by is a fractional number, like 0.1 or 0.11 then you'll have to separate your index from your number, like I think you originally had in your message where you had a and b instead of i and b. You could just make the loop index from 1 to 11 and then create the array index from it like arrayIndex = i / 10 and then use arrayIndex in z() or wherever.

Answer by Walter Roberson
on 18 Dec 2012

z = bsxfun(@times, i(:), b);


Answer by Sean de Wolski
on 18 Dec 2012

Code golf:


  1 Comment

Provided "i" is not complex, which it normally is ;-)

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!