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일
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

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!
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일
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에 대해 자세히 알아보기

질문:

2011년 6월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by