Maintain data type during variable assignment

3 views (last 30 days)
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?

Accepted Answer

Steven Lord
Steven Lord on 3 Jul 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

More Answers (0)

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!