Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
OPTIMIZED CODE FOR ARRAY OPERATION

Subject: OPTIMIZED CODE FOR ARRAY OPERATION

From: Lukas

Date: 22 Jul, 2010 12:20:22

Message: 1 of 5

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;

Subject: OPTIMIZED CODE FOR ARRAY OPERATION

From: Andy

Date: 22 Jul, 2010 12:44:04

Message: 2 of 5

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.

Subject: OPTIMIZED CODE FOR ARRAY OPERATION

From: Lukas

Date: 22 Jul, 2010 13:07:05

Message: 3 of 5

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@gmail.com> wrote in message <i29eej$2eb$1@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.

Subject: OPTIMIZED CODE FOR ARRAY OPERATION

From: Sean

Date: 22 Jul, 2010 13:11:06

Message: 4 of 5

"Andy " <myfakeemailaddress@gmail.com> wrote in message <i29eej$2eb$1@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);

Subject: OPTIMIZED CODE FOR ARRAY OPERATION

From: Lukas

Date: 22 Jul, 2010 13:42:04

Message: 5 of 5

Thank's a lot,

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

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us