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
Robert Cumming 2011 年 6 月 5 日

0 投票

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
Bruno 2011 年 6 月 5 日
alright cool this kinda works but the answer is in a matrix, but how can i get the answer as three arrays that the for loop throws out such as:
y(1)=[20;40;60]
y(2)=[40;80;120]
y(3)=[60;120;180]
thanks!
Robert Cumming
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
Matt Fig 2011 年 6 月 5 日

0 投票

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 ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2011 年 6 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by