How to define a variable as an integer that's equal to or greater than zero?

9 Ansichten (letzte 30 Tage)
I have the following if statements:
if struct_idx == 1 + 4*n % where n is an integer equal to or greater than zero
measurement_data(struct_idx).unit = 'SD1';
elseif struct_idx == 2 + 4*n % where n is an integer equal to or greater than zero
measurement_data(struct_idx).unit = 'SD2';
elseif struct_idx == 3 + 4*n % where n is an integer equal to or greater than zero
measurement_data(struct_idx).unit = 'SD3';
else struct_idx == 4 + 4*n % where n is an integer equal to or greater than zero
measurement_data(struct_idx).unit = 'SD4';
end
How can I turn the commented parts into working code?

Akzeptierte Antwort

Torsten
Torsten am 11 Jul. 2019
rest = mod(struct_idx,4);
if rest == 1
...
elseif rest == 2
...
elseif rest == 3
...
elseif rest == 0
...
end
  1 Kommentar
Steven Lord
Steven Lord am 11 Jul. 2019
Since you only have a small finite list of possible values for rest (assuming struct_idx is a real finite scalar) you could also use a switch statement.
Alternately, given the specific details of the user's code, just use rest directly without any if / elseif / end or switch statement.
rest = mod(struct_idx, 4);
rest(rest == 0) = 4;
unit = "SD" + rest; % If using a string is acceptable
unit = ['SD' num2str(rest)] % if rest is a scalar and you need a char vector

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Fangjun Jiang
Fangjun Jiang am 11 Jul. 2019
rem(struct_idx,4)==1

Community Treasure Hunt

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

Start Hunting!

Translated by