필터 지우기
필터 지우기

For a certain condition, how to replace a numerical value with text

조회 수: 6 (최근 30일)
mcm
mcm 2016년 10월 23일
댓글: Image Analyst 2016년 10월 23일
For example: if x == 0 replace 0 by 'normal'

답변 (1개)

John D'Errico
John D'Errico 2016년 10월 23일
A numeric variable cannot contain text. So one element of a vector cannot be the word 'normal', while the remainder remains numeric. To do that you would need to convert a vector to a cell array, but then simple computations on the cell array are much less easy to do.
To do what you explicitly asked is trivial though:
if x == 0
x = 'normal';
end
  댓글 수: 2
mcm
mcm 2016년 10월 23일
편집: Image Analyst 2016년 10월 23일
But I do i change all the value for an array (UPDRS1997) of 1x50 different values ranging from 0 to 4.
pick_year = input('Pick a year: either 1997 or 2013: ')
if pick_year == 1997
load('UPDRS1997')
for x = UPDRS1997
if x == 0
x = 'normal'
elseif x == 1
x = 'slight'
elseif x == 2
x = 'mild'
elseif x == 3
x= 'moderate'
elseif x == 4
x = 'severe'
end
end
end
Image Analyst
Image Analyst 2016년 10월 23일
If UPDRS1997 has 50 values in it, fine, but that code will overwrite x every time so it will have only the value that it has for UPDRS1997(end). Here is a better, more robust, general and flexible way:
pick_year = input('Pick a year: either 1997 or 2013: ')
filename = sprintf('UPDRS%d.mat', pick_year);
if exist(filename, 'file')
s = load(filename)
if pick_year == 1997
vec = s.UPDRS1997;
else
vec = s.UPDRS2013;
end
for k = 1 : length(vec)
if vec(k) == 0
x{k} = 'normal'
elseif vec(k) == 1
x{k} = 'slight'
elseif vec(k) == 2
x{k} = 'mild'
elseif vec(k) == 3
x{k} = 'moderate'
elseif vec(k) == 4
x{k} = 'severe'
end
end
else
message = sprintf('%s does not exist', filename);
uiwait(warndlg(message));
end
In this, the final result (badly named "x") is a cell array of 50 strings. It's not overwriting all the x like you did.

댓글을 달려면 로그인하십시오.

카테고리

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