How to assign values to cell array of characters (e.g., LeftArrowKey = 1)

조회 수: 1 (최근 30일)
James Crum
James Crum 2017년 12월 2일
답변: BhaTTa 2024년 10월 23일
I am trying to use a for loop to go through a cell array of character data that denote which key was pressed (LeftArrow, RightArrow) and change the LeftArrow cells to 0 and the RightArrow cells to 1. However, when I use the code below, the new matrix is larger in length than the original.
for item = 1 : length(OT1response_1)
if strcmp(OT1response_1{item},'RightArrow')
responses(item) = 1;
else
responses(item) = 0;
end
OT1converted_1 = (responses)
end

답변 (1개)

BhaTTa
BhaTTa 2024년 10월 23일
Hey @James Crum, I assume that ' OT1response_1' might have other keystroke entries other than 'LeftArrow' and 'RightArrow' this might be the possible reason for unintended behaviour, you can use the below corrected code to handle this edge case:
% Assuming OT1response_1 is your cell array of strings
OT1response_1 = {'LeftArrow', 'RightArrow', 'LeftArrow', 'RightArrow'}; % Example data
% Initialize the responses array with zeros
responses = zeros(1, length(OT1response_1));
% Loop through each element in the cell array
for item = 1:length(OT1response_1)
if strcmp(OT1response_1{item}, 'RightArrow')
responses(item) = 1;
elseif strcmp(OT1response_1{item}, 'LeftArrow')
responses(item) = 0;
else
error('Unexpected value in OT1response_1');
end
end
% Assign the converted responses to OT1converted_1
OT1converted_1 = responses;
% Display the result
disp(OT1converted_1);
0 1 0 1

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by