How to multiply Multidimensional Arrays with a column vector

I want to multiply A with B so that C(:,:,1) is equal to A(:,:,1)*B(1) and C(:,:,2) is equal to A(:,:,2)*B(2)
>> A = cat(3, [2 8; 0 5], [1 3; 7 9])
A(:,:,1) =
2 8
0 5
A(:,:,2) =
1 3
7 9
>> B=[1 2]'
B =
1
2
I'm looking to get this:
>> C=???
C(:,:,1) =
2 8
0 5
C(:,:,2) =
2 6
14 18

Answers (3)

Dear Tristan, here is the code which performs the task:
A = cat(3, [2 8; 0 5], [1 3; 7 9]);
B=[1 2]';
for i = 1:length(B)
C(:, :, i) = B(i) * A(:, :, i);
end
disp(C)
I hope it helps. Good luck!

5 Comments

is there any way to do it without using a loop?
I couldn't see any way to do it without loop. Maybe if I will have I will post here
The only way I can think of would be by transforming B into a multidimensional array like this:
>> B(:,:,1)=1;B(:,:,2)=2
B(:,:,1) =
1
B(:,:,2) =
2
>> bsxfun(@times,A,B)
ans(:,:,1) =
2 8
0 5
ans(:,:,2) =
2 6
14 18
but the real B I'm working with has too many numbers to type them all, any idea how I could do it?
You can do it like this:
C = cat(3, [], [], B);
This should work too
C=A.*permute(B,[3 2 1]),3);
Permute switches the rows in B (So the elements of a column vector) with the third dimension

Sign in to comment.

Clear Matlab solution according sixwwwwww and Tristan:
B=zeros(1,1,2);
B(:)=[1,2];
C=bsxfun(@times,A,B);

Categories

Asked:

on 28 Oct 2013

Commented:

on 14 Feb 2019

Community Treasure Hunt

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

Start Hunting!