Cell array display within if statements
Show older comments
Basically I have a few nested loops, and at some point if conditions are met, I want it to output a certain string. However, outputting that string is greatly slowing down my code. After testing, I found that it was only effected when accessing cell arrays.
For example:
tic
c={'test'};
for a=1:10000
for b=1:10000
if a>9999 && b>9999
c
end
end
end
toc
Above code results in:
c =
'test'
Elapsed time is 0.305766 seconds.
However,
tic
c={'test'};
for a=1:10000
for b=1:10000
if a>9999 && b>9999
c(1) %%<-- Added (1)
end
end
end
toc
Results in:
ans =
'test'
Elapsed time is 2.325998 seconds.
Adding the index of the cell array makes it almost 10x slower. Why?
Also things such as "toc" inside the if statement have the same result. If they're inside the 'if' statement, shouldn't they be ignored until the 'if' statement is true...
Accepted Answer
More Answers (1)
Guillaume
on 28 Sep 2015
Note that if your c is just {'test'} then c and c(1) are exactly the same thing: a cell array. The latter may be slower because you're asking matlab to return only a portion of the cell array (but it turns out it's actually the whole cell array).
To get the content of the cell array, use curly brackets:
c{1}
In all likelyhood, this is going to be much faster as this is just string display. With your code, you're asking matlab to display a cell array. I would assume the disp function (which you're calling implicitly) for a cell array has to: 1) figure the size of the cell array, 2) figure the content of each cell, 3) figure whether it can display that content, and if it can 4a) display that content, otherwise 4b) display a summary of the content.
It would also probably better to call disp explicitly. For a start, it shows better that you intend to display something. I personally would use sprintf:
disp(c{1});
%or
sprintf('%s\n', c{1});
Also, as far as I know matlab is better at optimising functions than scripts, so you may be better off putting your code in a function.
2 Comments
Robert Dylans
on 28 Sep 2015
WAT
on 28 Sep 2015
I think your problem is that doing anything at all inside loops like that isn't really MATLAB's specialty.
When I try your original example (the line consisting solely of 'c') I actually have a horrible running time (31.7 seconds) compared to 1.8 seconds if I change that line to 'disp(c)'. I get the exact same behavior if I change c to a double or anything else.
Categories
Find more on Loops and Conditional Statements 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!