How do I assign a text to a numerical value for an array inside of a for loop?

4 次查看(过去 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
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 个评论
mcm
mcm 2016-10-21
It's an scalar but with 50 different values ranging from 0 to 4. This wouldn't work either.
James Tursa
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
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));

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by