How to set up while loop to end with a specific count of strings
조회 수: 6 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Rajanya
2025년 6월 4일
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
참고 항목
카테고리
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!