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

12 次查看(过去 30 天)
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?

采纳的回答

Torsten
Torsten 2019-7-11
rest = mod(struct_idx,4);
if rest == 1
...
elseif rest == 2
...
elseif rest == 3
...
elseif rest == 0
...
end
  1 个评论
Steven Lord
Steven Lord 2019-7-11
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

请先登录,再进行评论。

更多回答(1 个)

Fangjun Jiang
Fangjun Jiang 2019-7-11
rem(struct_idx,4)==1

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by