From: Lukas on
Dear Matlab experts!

I have the following problem: 3D subarrays of a 4D array have to multipied by a 3D array and I wonder if this could be achieved more elegantly and efficiently avoiding for loops... (See code below...). Could "arrafun" used for it?

Many thanks in advance,

LS

My soluitons are the following:

Solution 1:

Sample_4D = ones(20,20,20,10000);
Rand_3D= rand(20,20,20);
Results = zeros(size(Sample_4D));

for i =1:size(Sample_4D,4)
Results(:,:,:,i) = Sample_4D(:,:,:,i).*Rand_3D;
end

Solution 2: Transform the 3D into a 4D matrix

Sample_4D = ones(20,20,20,10000);
Rand_3D= rand(20,20,20);
Rand_4D=zeros(size(Sample_4D));
Results = Rand_4D;

for i =1:size(Sample_4D,4)
Rand_4D(:,:,:,i) = Sample_3D;
end
Results = Sample_4D.*Rand_4D;
From: Andy on
Well, this is simpler to write than your first method:


newrand_3d = repmat(Rand_3D, [1 1 1 size(Sample_4D,4)]);
results = Sample_4D.*newrand_3d;

But it is in fact slower than the for loop.
From: Lukas on
Thank you Andy!

It looks better than my code. But the optimum would be to avoid to the loops and the mulitiplikation of the data. Any idea how to solve it?

"Andy " <myfakeemailaddress(a)gmail.com> wrote in message <i29eej$2eb$1(a)fred.mathworks.com>...
> Well, this is simpler to write than your first method:
>
>
> newrand_3d = repmat(Rand_3D, [1 1 1 size(Sample_4D,4)]);
> results = Sample_4D.*newrand_3d;
>
> But it is in fact slower than the for loop.
From: Sean on
"Andy " <myfakeemailaddress(a)gmail.com> wrote in message <i29eej$2eb$1(a)fred.mathworks.com>...
> Well, this is simpler to write than your first method:
>
>
> newrand_3d = repmat(Rand_3D, [1 1 1 size(Sample_4D,4)]);
> results = Sample_4D.*newrand_3d;
>
> But it is in fact slower than the for loop.

Fastest:
Results1 = bsxfun(@times,Sample_4D,Rand_3D);
From: Lukas on
Thank's a lot,

Lukas
>
> Fastest:
> Results1 = bsxfun(@times,Sample_4D,Rand_3D);