Filter löschen
Filter löschen

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

4 Ansichten (letzte 30 Tage)
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

Antworten (2)

James Tursa
James Tursa am 21 Okt. 2016
If UPDRS1997 is just a scalar you could do this:
conditions = {'normal','slight','mild','moderate','severe'};
x = conditions{UPDRS1997+1};
  2 Kommentare
mcm
mcm am 21 Okt. 2016
It's an scalar but with 50 different values ranging from 0 to 4. This wouldn't work either.
James Tursa
James Tursa am 21 Okt. 2016
Bearbeitet: James Tursa am 21 Okt. 2016
Your code above only tests for the integer values 0 to 4. What is supposed to happen for the other (fractional?) values?

Melden Sie sich an, um zu kommentieren.


Walter Roberson
Walter Roberson am 21 Okt. 2016
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));

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by