Simple nested For Loop Question

2 views (last 30 days)
Ben
Ben on 31 Oct 2014
Commented: Image Analyst on 31 Oct 2014
Hi,
Im pretty sure there is an obvious answer for my issue however for some reason I just can't get the code to work the way I want it. My current code is:
tic
a = zeros(4);
n=(1:4);
for x = [1 2 3 4]
for y = [5 6 7 8]
a(n) = x*y
end
end
toc
However thats one of many versions I've tried. Basically what I want to do is times the first value of X by the first, second, third then forth value of y and then do the same with second value of x and so on. My expected answer should be
a = 5 6 7 8
10 12 14 16
15 18 21 24
20 24 28 32
I swear I've done this a multiple times in complex situations previously. however I'm trying to show some people how use the code on a basic level and just can't seem to get it to work.
Any help would be appreciated.

Accepted Answer

Image Analyst
Image Analyst on 31 Oct 2014
Edited: Image Analyst on 31 Oct 2014
Try this:
tic
a = zeros(4);
for x = 1:4
for y = 5 : 8
a(x, y-4) = x * y
end
end
toc
a
  2 Comments
Ben
Ben on 31 Oct 2014
Whilst this does work i also need it to work with different numbers as well such as x and/or y = [1 4 9 10 18](basically a range with no pattern). However thank you for you help so far
Image Analyst
Image Analyst on 31 Oct 2014
Try this:
tic
x = [4, 5, 11, 3, 1]
y = [1, 4, 9, 10, 18]
a = zeros(length(y), length(x));
for row = 1 : length(y)
for col = 1 : length(x)
a(row, col) = x(col) * y(row);
end
end
toc
a

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!