필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
mcm
mcm 2016년 10월 21일
답변: Walter Roberson 2016년 10월 21일
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