creating a temporary variable

27 views (last 30 days)
This is a quick question. Compare
A = sparse(...); B = A - C;
and
B = sparse(...) - C;
Memory-wise spoken, is there a difference? Will the second one use less memory because I'm not creating a variable?

Accepted Answer

Walter Roberson
Walter Roberson on 3 Jan 2012
There will be very little memory difference. For a transient value, MATLAB creates everything about the storage except the symbol table entry with the name and a pointer to the descriptor.
  3 Comments
Ingo
Ingo on 3 Jan 2012
Alright then.
Additionally, I tested this whole thing (only "quick'n'dirty", though) and I couldn't notice any memory difference.
Thanks!

Sign in to comment.

More Answers (1)

Nicholas
Nicholas on 3 Jan 2012
Did you try using tic toc?
tic
A = sparse(magic(3));
B = A - C;
disp(toc)
tic
B = sparse(magic(3)) - C;
disp(toc)
In any case the result depends on matrix dimensions and matrix initialization. If you want to improve memory management you should initialize a matrix/vector first and than try to improve matrix calculation.
  3 Comments
Ingo
Ingo on 3 Jan 2012
Yeah, I know that writing it in C would be more efficient. The advantage of Matlab, however, is the simple fact, that I don't have to implement all the mathematical stuff.
My code is pretty fast, I believe. If there was any way to make it faster in Matlab, I'd do it. So I'm looking for ways. But if not, that's okay, too – creating, processing and plotting 100.000 data points on my several years old laptop within seconds or minutes sounds more than acceptable to me. ;)

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!