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

1 次查看(过去 30 天)
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