Вопрос

I know in Matlab you can use "nice" vector operations like A*B or A.*B

If you have

A=[2, 2];
B=[3, 1];

it is logic, you cannot use A*B. You can use A.*B what is A[1]*B[1], A[2]*B[2] and result is [6, 2].

In many "scripts" I am writing I often need to use something, that results in:

[6, 6; 
2, 2]

So basically i need to use forcycle (something like:):

C=zeros(2,2);
for i=1:size(A,1)
  C(i,:)=A*B(i);
end

And i would like to ask, how (if it is possible) to rewrite this without forcycles? Is it possible? This 2 vectors of 2 elements is maybe bad for understanding what i need. So another example:

A=[1,2,3,4,5]
B=[2,4]

result:

[2,4,6,8,10;
4,8,12,16,20]

in short SOMETHING like:
C(1:end <==== GO BY ONE ELEMENT,:)=A*B(1:end <===== GO BY ONE ELEMENT)
--> Take WHOLE vector A and multiply it by FIRST element in B and save it at FIRST row in matrix what have A columns and B rows..
--> Take WHOLE vector A and multiply it by SECOND element in B and save it at SECOND row in matrix what have A columns and B rows..
--> Take WHOLE vector A and multiply it by THIRD element in B and save it at THIRD row in matrix what have A columns and B rows..
--> ...
--> Take WHOLE vector A and multiply it by LAST element in B and save it at LAST row in matric what have A columns and B rows..

Это было полезно?

Решение

You can use bsxfun for this purpose

P = bsxfun(@times,A,B')

This gives

A =  1     2     3     4     5
B =  2     4


P =  2     4     6     8    10
     4     8    12    16    20

Другие советы

An alternative solution is to use matrix multiplication:

[ones(size(B))'*A].*[B'*ones(size(A))]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top