MATLAB Answers

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

9 views (last 30 days)
Heidi Mäkitalo on 11 Jul 2019
Commented: Steven Lord on 11 Jul 2019
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?

#### 0 Comments

Sign in to comment.

### Accepted Answer

Torsten on 11 Jul 2019
rest = mod(struct_idx,4);
if rest == 1
...
elseif rest == 2
...
elseif rest == 3
...
elseif rest == 0
...
end

#### 1 Comment

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

Sign in to comment.

### More Answers (1)

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

#### 0 Comments

Sign in to comment.

Sign in to answer this question.

Translated by