How do I assign a text to a numerical value for an array inside of a for loop?
2 次查看(过去 30 天)
显示 更早的评论
Hi have the following for loop and for each x (0 to 4) I want to assign a specific word to it.
pick_year = input('Pick a year: either 1997 or 2013: ')
if pick_year == 1997
load('UPDRS1997')
for x = UPDRS1997
if x == 0
REPLACE X BY 'normal'
elseif x == 1
REPLACE X BY 'slight'
elseif x == 2
REPLACE X BY 'mild'
elseif x == 3
REPLACE X BY 'moderate'
elseif x == 4
REPLACE X BY 'severe'
end
end
end
回答(2 个)
James Tursa
2016-10-21
If UPDRS1997 is just a scalar you could do this:
conditions = {'normal','slight','mild','moderate','severe'};
x = conditions{UPDRS1997+1};
2 个评论
James Tursa
2016-10-21
编辑:James Tursa
2016-10-21
Your code above only tests for the integer values 0 to 4. What is supposed to happen for the other (fractional?) values?
Walter Roberson
2016-10-21
It is not possible to replace a numeric value with a string in a numeric array, except in the case where the numeric value is the only thing inside a cell of a cell array.
You know, you don't need a loop at all:
state_vals = [0, 0.5, 1, 1.83, 2, 2.29, 3, 3.14, 3.74, 4];
states = {'normal', 'half-slight, 'slight', 'noticeable but not bad', 'mild', 'needs buffing', 'moderate', 'not doing so well', 'oh this is bad', 'severe'};
pick_year = input('Pick a year: either 1997 or 2013: ')
filename = sprintf('UPDRSscores_%d.mat', pick_year);
fieldname = sprintf('UPDRS%d', pick_year');
if ~exist(filename, 'file')
error('file "%s" does not exist', filename);
end
datastruct = load(filename);
pick_data = datastruct.(fieldname); %pull it out of what was loaded from the file
num_states = length(pick_data);
[tf, state_idx] = ismembertol(pick_data, state_vals);
state_names = cell(1, num_states);
state_names(~tf) = {'Unknown'};
state_names(tf) = states(state_idx(tf));
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!