필터 지우기
필터 지우기

insert string in a numerical vector

조회 수: 5 (최근 30일)
jimaras
jimaras 2014년 2월 2일
답변: Jan 2014년 2월 2일
Hello there,
I have a value vector (1-by-n) and I am trying to replace the number in a given element by a string. How can I achieve this?
my code is:
n=length(A);
k=100;
for i=1:n
if A(i)<k
A(i)= 'wrong';
end
end

답변 (3개)

Image Analyst
Image Analyst 2014년 2월 2일
You need to do a cell array to do that:
A = {200, 99, 300}
n=length(A);
k=100;
for i=1:n
if A{i} < k
A{i} = 'wrong';
end
end
celldisp(A)
  댓글 수: 10
Image Analyst
Image Analyst 2014년 2월 2일
Here's an explanation of cell arrays: http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F It will let you mix numbers, strings, structures, or any type of variable you want into a single array. But they're a pain to deal with. People are always using parentheses instead of braces and vice versa even though you can use both, you just have to use them at the right time. That's why it's complicated. For your "K", it's not the size - your K is a simple numerical array no matter the size. But if you wanted the 3rd element of K to be "wrong" instead of 6, now it can't be a simple numerical array anymore. It has to be a cell array because that's the only type of array that can mix numbers and strings. Well, okay, you could have an array of structures too, which is simpler than cell arrays to understand, but somewhat different also. Why don't you give me the "big picture"? Why do you want to do what you asked? Why do that (put in strings) instead of fixing the data or flagging it with nan's?
jimaras
jimaras 2014년 2월 2일
Because I want the observer of the filtered data to be able to see the current value of the i element of the array and the comment which says that this value is 'inactive'. Thanks a lot for your help, it is really precious.

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


Jan
Jan 2014년 2월 2일
It is better to keep the data and the classifications in different variables. This can be done without loops also, e.g.:
Vol = rand(1, 100);
B = cell(1, 100);
C = cell(1, 100);
B(Vol < 0.3) = {'inactive'};
C(Vol > 0.9) = {'illiquid'};

Azzi Abdelmalek
Azzi Abdelmalek 2014년 2월 2일
n=length(A);
k=100;
B=num2cell(A);
for i=1:n
if A(i)<k
B{i}= 'wrong';
end
end
  댓글 수: 2
jimaras
jimaras 2014년 2월 2일
I have tried both ways but none of them works. Here is my new code:
n=length(Vol);
B=num2cell(Vol);
C=num2cell(Int);
for i=1:n
if Vol(i) < VolMin
B{i} = 'inactive';
end
if Int(i)< IntMin
C{i}= 'illiquid';
end
end
Jan
Jan 2014년 2월 2일
@jimaras: Please donot write "does not work", but explain the problem: Do you get an error message or do the results differ from your expectations?

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

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by