Put a matrix back to zeros (looking for an elegant solution)

Hello,
I have one matrix that is generated withe zeros:
A=zeros(5,4);
And, during the cycle matrix A get different values to make some math. I want that in the end of the cycle the matrix A come back to is original values so it can start it all over. Is there any elegant solution or should i just use the same code that used to initialize the matrix?

 Accepted Answer

A(:) = 0;

9 Comments

This takes about 50% longer on my system:
[t1,t2] = deal(0);
A = zeros(2000);
for ii = 1:100
tic
A = zeros(2000);
t1=t1+toc;
tic
A(:) = 0;
t2=t2+toc;
end
[t1 t2]
%ans= 0.2117 0.3609
Sounds like something Mathworks should be optimizing then ;-)
What about
A = A - A;
?
2% slower than A(:)=0.
We're aware of it Walter, don't worry!
Surprising. I cannot test this currently:
tic;
for ii = 1:100
A = zeros(2000);
A(1, 1:10) = rand(1, 10);
end
toc
tic;
A = zeros(2000);
for ii = 1:100
A(:) = 0;
A(1, 1:10) = rand(1, 10);
end
toc
Actually allocatiing the array should be more expensive than setting it to 0.
When I test in a development version, the timings cannot be reliably distinguished. A(:) = 0 did peak higher than zeros(2000), but the times strongly overlapped, and zeros(2000,2000) tended higher than zeros(2000) but again with overlap. And what trended as lowest was A = A - A
Tossing the possibilities into a function in a .m file might make a significant difference in this situation.
@Walter: As far as I understand, you do not observe a 50% difference on your system.
Now that I have turned off the processes using 7.1 of my 8 CPUs, I get much more reproducible results. Times still overlap, but in my test, A(:)=0 tends to be lower, and A=A-A; tends to be lower still. Maximum variability between all the possibilities was 0.305 (A-A) to 0.319 (zeros(2000,2000)). Not even close to 50%. (This for a simplified version without the rand())
R2012a on MacBook Pro, OS-X Lion, i7 CPUs, the A(:)=0 consistently tests slightly faster when I use Sean's code, not slower at all.
Sean, did you forget to turn off your disk defragger while you were testing? :)

Sign in to comment.

More Answers (1)

That's what I would do. zeros is the most elegant want to create zeros :)

2 Comments

I thought there was something like A=clean; And it would clean the matrix :D Something like harry potter style :D
You could write clean() to do this if you wanted, considerably less elegant though...

Sign in to comment.

Categories

Tags

Community Treasure Hunt

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

Start Hunting!