How to optimize this code to run faster?
3 views (last 30 days)
Show older comments
Hello,
I have a code that is attached that I am trying to optimize in order for it to run faster.
It contains a lot of for loops (which are very slow, I know). In the beginning this was the only way for me to code this as a beginner.
This is a small part of my original code, but it lacks in speed when I analyze it in MATLAB. It is very very slow, especially when I work with a large 3D set of images.
Can anyone help me with this, on how to optimize it. I would really appreciate it.
Thanks in advance!
0 Comments
Answers (1)
Adam Danz
on 18 Aug 2018
Your variable names induce anxiety in me :D
I'll tidy up the first for-loop so you can see how that's done.
I assume ndims(M) == 3 (ie, 'M' is 3D array)
If that's the case, 'Mmat' is a matrix and 'min1' is a column vector and
for ij1=1:numImages
Mmin1(:,ij1)=Mmat(:,ij1)-min1(ij1,:);
end
can be replaced by
Mmin1 = Mmat - min1';
This works because the number of columns in Mmat equals the number of columns in min1' (transposed).
You could test that these two methods produced the same results by performing both of them and storing the results under different variable names. Then use isequal()
isequal(Mmin1, Mmin1_b)
Most of your for-loops follow similar logic so why don't you give it a shot and follow-up with specific areas where you got stuck, stating what you tried, etc.
12 Comments
Adam Danz
on 19 Aug 2018
Wow, Walter helped you out a lot! I'll chip in two more examples.
numPix=zeros(numImages,1);
for ii=1:numImages
numPix(ii) = numel(jj(ii).PixelValues);
end
can be replaced by
numPix = cellfun(@numel, {jj.PixelValues}');
As for
numPixix=table(numPix);
numPixx=table2cell(numPixix);
for qq=1:ii
numPixxx{qq, 1}=[1:(numPixx{qq, 1})]';
end
assuming numPix is a vector (double, integers), it's replacement would be
numPixxx = cellfun(@(x)1:x, num2cell(numPix), 'UniformOutput', false);
Given the tools you learned from Walter and from these two examples, why don't you try the rest on your own. Google and this forum are great primary resources when getting stuck. If you've tried several methods and can't understand why they aren't working, follow-up here and include the methods you've tried so we can help set things straight.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!