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}
Andrei Bobrov
2011 年 6 月 6 日
y = b'*d*a
カテゴリ
ヘルプ センター および 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!