Adding Element based on Condition to Structure with For Loop
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Voss
2023-2-11
This:
if MasterDataMeasurement.CurrentTrainingTrialRatio(i) == 1.8125 | 1.875
should be this:
if MasterDataMeasurement.CurrentTrainingTrialRatio(i) == 1.8125 || MasterDataMeasurement.CurrentTrainingTrialRatio(i) == 1.875
2 个评论
Voss
2023-2-11
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!