Maintain data type during variable assignment

9 vues (au cours des 30 derniers jours)
Ryan Mihelich
Ryan Mihelich le 3 Juil 2019
Commenté : Ryan Mihelich le 4 Juil 2019
Hello,
Let's say I have the following code:
a = uint32(1);
a = 2; % Changes the type back to double
What is the sytanx for preserving the existing uint32 data type IF I didn't want to keep doing uint32() casts on all new data. I remember in the past there was something like:
a := 2;
% or
a ?= 2;
% BUT THESE ARE BOTH WRONG
But I can't for the life of me find the right assignment operator that did this.
Anyone know how to do this?

Réponse acceptée

Steven Lord
Steven Lord le 3 Juil 2019
Subscripted assignment converts the data on the right side of the equals sign to the type of the variable on the left side (if that variable already exists.)
Non-subscripted assignment overwrites the variable on the left side (or creates it if it didn't exist) with the data on the right side.
A = uint8(1);
A(:) = 2 % A is a uint8 scalar containing the value 2
B = uint8(1);
B = 2 % B is a double scalar containing the value 2
whos A B
In the case of B, I could have assigned any sized data into it because I'm directly overwriting the variable. In the case of A, the value on the right side has to have the same number of elements as A or must be a scalar.
A = uint8(magic(4));
A(:) = (1:16)+50 % Same number of elements but different shape works
A(:) = 99 % Scalar works
A(:) = 1:10 % Does not work
  1 commentaire
Ryan Mihelich
Ryan Mihelich le 4 Juil 2019
That's it!! Perfect, thanks!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by