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

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

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.

Tag Activity for This Thread
Tag Applied By Date/Time
bsxfun Sean de 22 Jul, 2010 09:14:07
code optimzation Lukas 22 Jul, 2010 08:24:04
array Lukas 22 Jul, 2010 08:24:04
rssFeed for this Thread

Contact us