How do multiply all elements inside a for loop by an array
显示 更早的评论
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
回答(3 个)
Robert Cumming
2011-6-5
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 个评论
Bruno
2011-6-5
Robert Cumming
2011-6-5
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
2011-6-5
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}
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!