hello all, what are the main uses of functions 'zeros' and 'ones' ? Why we use them ? thank you

 Réponse acceptée

James Tursa
James Tursa le 6 Nov 2015
A couple of examples.
zeros is often used to allocate a variable to a known size, then downstream code will fill in the individual elements. E.g.,
x = zeros(1,5); % Pre-allocate x to the correct size
for k=1:5
x(k) = k^2; % Fill in the individual elements
end
ones could be used to allocate a variable with a constant. E.g.,
x = ones(1,5) * 7; % Allocate a variable and fill it with 7's

3 commentaires

Stephen23
Stephen23 le 6 Nov 2015
Modifié(e) : Stephen23 le 6 Nov 2015
Array preallocation is described very well in the documentation:
Understanding array preallocation is critical for writing efficient loops in MATLAB.
Marcus Sandquist Lignell
Marcus Sandquist Lignell le 6 Nov 2015
In addition to this, when using for loops; pre-allocating a matrix in the correct size for the output results will speed up your solve time.
yogesh jain
yogesh jain le 6 Nov 2015
Thank you very much all (Mr. James Tursa ,Stephen Cobeldick and Marcus Sandquist Lignell) . That was pretty useful :)

Connectez-vous pour commenter.

Plus de réponses (1)

Dimithra Anton
Dimithra Anton le 13 Sep 2020
Modifié(e) : Dimithra Anton le 13 Sep 2020

0 votes

zeros(length(numbers),2)
what about this??? what does (numbers) do and why is the number of columns 6?

1 commentaire

numbers is an array that is being passed into the length function (or it is a function that can be called with no input arguments and whose first output is being passed into the length function.)
I would not expect that command to return an array with six columns. Assuming you haven't written or downloaded a zeros.m function that is taking precedence over the built-in function it should return a matrix with two columns.
which -all zeros

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by