# How can I set the arrays dimensions?

434 vues (au cours des 30 derniers jours)
Jay le 19 Nov 2016
Commenté : Walter Roberson le 19 Nov 2016
How do I set the dimensions of an array so that it wont change?
i.e. rather than stating a vector being a 3 x 1 of zeros using the closed bracket specifiers "[0;0;0]"?
I have tried using curved brackets to specify the dimensions " a(3,1) = zeros, but if the input exceeds the initialized dimensions, no error is thrown.
The closed bracket dimension specifier is not practical for large dimension arrays.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponses (3)

James Tursa le 19 Nov 2016
You can't "freeze" the size of native variables in MATLAB. They are free to change size at any time. (You could make an OOP class that forces the size to be what you want, but I don't think that is what you are really asking). E.g., to initialize a large array:
a = zeros(1,1000000); <-- sets "a" to a large vector
But that won't stop you from subsequently doing this:
a = 5; <-- sets "a" to a scalar
And the reverse is also true. Just by initializing a variable to a small number of elements will not prevent growing it dynamically later on in your code. That's just the way MATLAB works.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Jay le 19 Nov 2016
Thanks guys,
I was hoping for a way to fix the dimensions but it is what it is.
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Walter Roberson le 19 Nov 2016
You can store the array somewhere and give the user accessor functions.

Connectez-vous pour commenter.

Walter Roberson le 19 Nov 2016
a = zeros(3,1);
However, numeric arrays cannot be forced to be a fixed size. If the user writes to an element outside the range, the array will be extended. You would need to create a new object class for fixed-size arrays.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by