Replacing a cell value in a struct
35 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
deejt
el 19 de En. de 2021
Editada: Image Analyst
el 20 de En. de 2021
Hello,
I have a struct with 4 fields.
One field contains my conditions (3 conditions, named using strings)
Now I want to replace the strings with numbers. How is that possible? So far I could not find anything :( Is this even possible?
Help is much appreciated!
0 comentarios
Respuesta aceptada
Image Analyst
el 19 de En. de 2021
This works:
% Identify what number should replace what character vector.
replacements = {'condi1', 1; 'condi2', 2; 'condi3', 3}
% Make cell array for Conditions
caConditions = {'condi1' 'condi2' 'condi3' 'condi3' 'condi1' 'condi3' 'condi2'}
% Create the whole structure array.
s = struct('subjectnumber', {1 1 1 1 1 1 1}, ...
'condition', caConditions, ...
'rt',{0.12 0.11 0.8 0.9 0.13 0.6 0.12}, ...
'point',{0 40 40 40 20 20 0})
for k = 1 : numel(s)
thisCondition = {s(k).condition}; % Character vector like 'condi1', or 'condi2', etc.
% Compare this condition to the list of them in column 1 of replacements
% and find out which row contains the replacement.
[~, row] = ismember(thisCondition, replacements(:, 1));
% Replace it with the number in column 2
s(k).condition = replacements{row, 2};
end
2 comentarios
Image Analyst
el 20 de En. de 2021
Editada: Image Analyst
el 20 de En. de 2021
Are you saying that you could have 25 thousand different strings? If so, rather than a look up table like I used, you'd need to use something like sscanf() to parse/extract the number out of the character string.
Más respuestas (2)
Image Analyst
el 19 de En. de 2021
Yes. For example to set the "condition" field to the number 5, do this:
yourStruct.condition = 5;
It doesn't matter that it used to be a string.
Attach your structure in a .mat file, or give code to create it, if you still have problems.
4 comentarios
Image Analyst
el 19 de En. de 2021
AGAIN:
Attach your structure in a .mat file, or give code to create it, if you still have problems.
I need it because I'm not sure how condition is what you showed : 3 character arrays. It can be a character matrix, a string vector, or even a cell array, but I don't know what you have or how you displayed that. Plus answer Bob's questions.
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!