Adding Element based on Condition to Structure with For Loop

2 views (last 30 days)
I have a structure that has a series of numbers in one of it's fields, the CurrentTrainingTrialRatio, and I am trying to iterate through a for loop to extract the SliderError and the TrialNumber when the CurrentTrainingTrialRatio is equal to 1.8125 or 1.875. Instead of populating the structure field with just the SliderError values for those ratios, it seems to be including all of them. I'm not sure why this is happening because when I test my logical comparisons individually they seem to work as expected.
% Convert to Structure
MasterDataMeasurement = table2struct(MasterDataMeasurement,"ToScalar",true);
MasterDataMeasurementSlowRatios = struct('SliderError',[],'TrialNumber',[]);
SlowRatiosIndexCounter = 1;
for i=1:height(MasterDataMeasurement.TrainingTrialsBool)
if MasterDataMeasurement.TrainingTrialsBool(i) == 1
if MasterDataMeasurement.CurrentTrainingTrialRatio(i) == 1.8125 | 1.875
MasterDataMeasurementSlowRatios.SliderError(SlowRatiosIndexCounter) = MasterDataMeasurement.SliderError(i);
SlowRatiosIndexCounter = SlowRatiosIndexCounter + 1;
end
end
end

Accepted Answer

Voss
Voss on 11 Feb 2023
This:
if MasterDataMeasurement.CurrentTrainingTrialRatio(i) == 1.8125 | 1.875
should be this:
if MasterDataMeasurement.CurrentTrainingTrialRatio(i) == 1.8125 || MasterDataMeasurement.CurrentTrainingTrialRatio(i) == 1.875
  2 Comments
Spencer Ferris
Spencer Ferris on 11 Feb 2023
That did it, thanks! Can I ask why you used || instead of | here? I've been trying to figure out the difference unsuccessfully.
Voss
Voss on 11 Feb 2023
One difference is that "||" is for comparing scalars, and "|" is for comparing non-scalar arrays (e.g., vectors, matrices, etc.). Either one would work here since "|" also works for scalars, and you're dealing with scalars here.
Another difference is that "||" "short-circuits". That is, if the first condition is true in the case of "||", then the second condition isn't checked, because "true or something else" is always true. (&& short-circuits in case the first condition is false because "false and something else" is always false.)
An example of where short-circuiting is useful would be: say you have a structure S and you want to do something in case S.a is 1, but S may not have the field 'a'. If you say, "if isfield(S,'a') & S.a == 1" you'd get an error evaluating the second condition if S doesn't have the field 'a', but if you say "if isfield(S,'a') && S.a == 1", there'd be no error because the second condition is not checked if S doesn't have 'a' because the first condition was false.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!