How to set up while loop to end with a specific count of strings
8 views (last 30 days)
Show older comments
I have a matrix with a number of reaction times that I would like to convert into a matrix only containing the reaction times of interest. In the matrix I have a row full of strings (e.g. 'Response') and next to it a row full of reaction times. I need only the reaction time next to the first 'Response'. Since the position of this first 'Response' is different for every trial, I need to set up a while loop, but I don't know how to tell Matlab to stop at the first count of 'Response'.
Any help is much appreciated.
0 Comments
Answers (1)
Rajanya
on 4 Jun 2025
The 'break' statement can be used to terminate a loop immediately once an exit condition is met- in this case, when the string "Response" is encountered for the first time - see https://www.mathworks.com/help/matlab/ref/break.html.
Since the objective is to extract only the reaction time corresponding to the first occurrence of "Response", an alternative approach that avoids the use of explicit loops is to use the 'find' function - see here, in combination with the 'strcmp' function.
idx = find(strcmp(<your_matrix_strings/keys>, 'Response'), 1, 'first'); %the '1' ensures only one element from first
'strcmp' compares all the string names in the matrix with "Response" and creates a logical array based on the same.
'find' then gets the first occurrence of a '1' (if found) from the logical array and the index is stored in 'idx'. This index can be used to extract the reaction time from the matrix corresponding to the first 'Response'.
To learn more about 'strcmp', refer to its documentation by executing the following command from MATLAB Command Window-
doc strcmp
Thanks.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!