How do multiply all elements inside a for loop by an array
Show older comments
basically I want to solve this: I have the array a c= a*b where a =2 and b =[1 2 3] so c =[ 2 4 6] I want to multiply each element of c by another array called d= [ 10 20 30]. Obviosuly the arrays are of different sizes so I can't seem to get it to work. The result I want to get is this: three arrays, each element of c multiplied to d
y = [20 40 60] [40 80 120] [60 120 180]
my code so far is this: clear all close all
a=2 b= [1 2 3]
d=[ 10 20 30]
for i=1:length(b)
c(i)=a*b(i);
for j=1:length(d)
y(j)=c*d(j);
end
end
Answers (3)
Robert Cumming
on 5 Jun 2011
a=2;
b= [1 2 3];
d=[10 20 30];
c=a*b;
y=zeros(3,3);
for ii=1:length(c)
y(ii,:) = d(ii)*c;
end
2 Comments
Bruno
on 5 Jun 2011
Robert Cumming
on 5 Jun 2011
what you've written is not possible. You cant put 3 numbers into a single elemnt. The closest you can get is to use cell arrays.
initialise by yy=cell(3,1)
and in the loop use yy{ii} = d(ii)*c
Note: cell arrays are indexed by curly brackets {}
Matt Fig
on 5 Jun 2011
c = [2 4 6];
d = [10 20 30];
y = bsxfun(@times,c.',d)
Or if you really must have a cell array:
y = arrayfun(@(x) times(x,d),c,'Un',0);
Not use cell indexing to get at each vector:
y{1}
y{2}
y{3}
Andrei Bobrov
on 6 Jun 2011
y = b'*d*a
Categories
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!