XaBerr
XaBerr

Reputation: 360

How to do multiplication in third dimension in matlab?

I want to do this multiplication between the LP 2x2 matrix and the H 2x1 vector.

LP = @(theta) [cos(theta) .^ 2, sin(theta) .* cos(theta); sin(theta) .* cos(theta), sin(theta) .^ 2];
H = [1; 0];
LP(theta) * H

If I pass theta as a scalar (e.g. 0 or pi) everything works. But, I want to pass a vector of theta to plot the results. When I do LP(0:0.01:2*pi) * H things start to break obtaining a 2x(2*100) instead of 2x1x100.

figure();
hold on;
filtering = LP(0:0.01:2*pi) * H;
plot(0:0.01:2*pi, filtering(1,:)); % x
plot(0:0.01:2*pi, filtering(2,:)); % y

My question is, there is a way that I can build my equation in matrix form avoiding loops?

Upvotes: 0

Views: 388

Answers (1)

James Tursa
James Tursa

Reputation: 2636

theta = 0:0.01:2*pi; % your vector of angles
LPcell = arrayfun(LP,theta,'uni',false); % cell array of 2D matrices
LP3 = cat(3,LPcell{:}); % 3D array made of 2D pages
result = pagemtimes(LP3,H); % 3D matrix multiply with the 2D pages

If you have an older version of MATLAB that doesn't have the pagemtimes( ) function, you could download similar functions from the FEX to do the 3D matrix multiply (e.g., mmx, mtimesx, multiprod)

Alternatively, instead of doing the arrayfun( ) stuff above to generate the 3D array you could rewrite your LP function handle as a vectorized version to get the 3D array you want from the outset.

Upvotes: 1

Related Questions