Maintain data type during variable assignment

조회 수: 8 (최근 30일)
Ryan Mihelich
Ryan Mihelich 2019년 7월 3일
댓글: Ryan Mihelich 2019년 7월 4일
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?

채택된 답변

Steven Lord
Steven Lord 2019년 7월 3일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by