Can anyone please clarify "what's the difference when a matrix is declared as zerosfrom ones"?

for eg:
arr=zeros(row,col); #create a matrix of size row X col with all elements #initialized to zero #similarly arr1=ones(row,col); #do the same except the initialized elements will be all 1's.
My doubt is why a matrix need to be declared zeros for computation??? Or Whats the basic idea behind initializing to all zeros??

Answers (2)

zeros is recommended to be used for preallocation purpose. Below is the link to the documentation. See the section Preallocating Arrays

4 Comments

sir,thanks for the link.I do understand the concept behind preallocation of arrays.But my question is why "zeros" is used rather than "ones".Do both provide same result? Which of the above provide better results?and why? please do reply..
I'm purely guessing here but I think it has to do with lower level implementations. My guess is that zeros simply allocate the memory, sort of like "static variable" in C, but to use ones, there is an extra step of assignment.
I think they both have to be assigned, otherwise the memory would just be whatever value they had last.
Memory initialized to 0 can, in some cases, be initialized by hardware "demand zero paging", in which a memory page is zeroed at the hardware level instead of having to write zeroes to it.

Sign in to comment.

  • it is common in problems for a result of 0 not to be possible but 1 to be possible, so 0 is more likely "available" to act as a marker that an element is not filled yet
  • 0 is the only numeric value that is logical "false" but all non-zero values are logical "true", making writing logical tests easier
  • 0 is the same in integer and floating point representation
  • 0 is the "no element here" marker for sparse arrays
  • 0 is the identity element for cumulative summing, which turns out to be more common than cumulative multiplications

Categories

Asked:

on 14 Mar 2013

Community Treasure Hunt

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

Start Hunting!