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

조회 수: 10 (최근 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