2D slices' multiplication from 4D matrix
Show older comments
Hello,
this loop creates a (2x2x3) matrix M, for a value of f (the other variable have been defined earler), and multiplies each 2D slice among the 3rd dimension, with its next one to get the p0u0 (2x2) matrix. Is it possible, with vectorised code to do the same in a range of f (for example f=linspace(50,1000,N)), create a 4th dimension on M (2x2x3xN) and get the p0u0 as a (2x2xN) matrix for each value of f (am trying to avoid long loops)? Sorry if it's too obvious; trying to get the hang of it.
-------------------------------------------------------------------
PL=1;
uL=0;
p0u0=1;
pLuL=[PL; uL];
f=300;
for i=1:3;
k(i)=(2*pi*f/c).*sqrt(a(i) - (j*s(i)*ph(i))./(2*pi*f*(p0c/c)));
z(i)=(p0c/ph(i)).*sqrt(a(i) - (j*s(i)*ph(i))./(2*pi*f*(p0c/c)));
M1(i)=cos(k(i)*L(i));
M2(i)=j*z(i)*sin(k(i)*L(i));
M3(i)=(j*sin(k(i)*L(i)))/z(i);
M4(i)=cos(k(i)*L(i));
M(:,:,i)=[M1(i) M2(i); M3(i) M4(i)];
p0u0=p0u0*M(:,:,i);
end
p0u0=p0u0*pLuL; Z=p0u0(1)/p0u0(2);
------------------------------------------------------------------
This alteration would give me a M(2x2x3xN) matrix, but I can't get the 2D-slices' multiplications done to get the p0u0 matrix..
-----------------------------------------------------------------
PL=1; uL=0; p0u0=1; pLuL=[PL; uL]; f=linspace(50,1000,N);
for i=1:3;
k(i,:)=(2*pi*f/c).*sqrt(a(i) - (j*s(i)*ph(i))./(2*pi*f*(p0c/c)));
z(i,:)=(p0c/ph(i)).*sqrt(a(i) - (j*s(i)*ph(i))./(2*pi*f*(p0c/c)));
M1(i,:)=cos(k(i,:)*L(i));
M2(i,:)=j*z(i,:).*sin(k(i,:)*L(i));
M3(i,:)=(j*sin(k(i,:)*L(i)))./z(i,:);
M4(i,:)=cos(k(i,:)*L(i));
M(:,:,i,:)=[cat(4, M1(i,:), M2(i,:)); cat(4, M3(i,:), M4(i,:))];
end
M=permute(M, [1,4,3,2]);
-------------------------------------------------------------------
I'd appreciate any hints..
Answers (1)
Sean de Wolski
on 2 Dec 2011
Without looking through what you've done, the goal seems pretty straight forward and loops should be able to handle it well (and probably faster for large matrices since they don't chew up as much memory)
%Big sample data
A = repmat(magic(200),[1,1,300]); %large sample data
B = zeros(size(A)-[0 0 1]); %1 shorter in 3rd dimension
tic
for ii = 1:size(B,3)
B(:,:,ii) = prod(A(:,:,ii:(ii+1)),3); %forward slice array product
%B(:,:,ii) = A(:,:,ii)*A(:,:,(ii+1)); %or matrix multiplication
end
toc
Elapsed time is 0.122935 seconds. Elapsed time is 0.122357 seconds.
Categories
Find more on Just for fun in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!