필터 지우기
필터 지우기

I want to create a new column with words that are atributed regarding the numerical values of another column. How can I proceed?

조회 수: 1 (최근 30일)
I have a column with "consumption" and values range between 3000 and 8000.
From 3000 to 4000, I want "low" in the new column; From 4000 to 7000, I want "medium"; From 7000 to 8000, I want "high".
How can I create this new column?

채택된 답변

Walter Roberson
Walter Roberson 2016년 10월 24일
It is not possible to put a string into a numeric matrix. You will need to use a table() or a cell array.
NewColumn = repmat( {''}, length(consumption), 1);
mask = consumption >= 3000 & consumption <= 4000;
NewColumn(mask) = cellfun(@(S) [S, 'low'], NewColumn(mask), 'Uniform', 0);
mask = consumption >= 4000 & consumption <= 7000;
NewColumn(mask) = cellfun(@(S) [S, 'medium'], NewColumn(mask), 'Uniform', 0);
mask = consumption >= 7000 & consumption <= 8000;
NewColumn(mask) = cellfun(@(S) [S, 'high'], NewColumn(mask), 'Uniform', 0);
The code would be considerably simpler if your ranges did not overlap -- you have defined 4000 as belonging to both low and medium, and you have defined 7000 as belonging to both medium and high.
  댓글 수: 2
Eduardo Rocha
Eduardo Rocha 2016년 10월 24일
Of course I don't want to overlap the ranges.. Thank you very much, it worked perfectly :)
Walter Roberson
Walter Roberson 2016년 10월 24일
I will have to guess about which way you want the overlap to be resolved.
NewColumn = cell( length(consumption), 1 );
NewColumn(consumption < 3000) = {'Forest Fire'};
NewColumn(consumption >= 3000 & consumption < 4000) = {'low'};
NewColumn(consumption >= 4000 & consumption < 7000) = {'medium'};
NewColumn(consumption >= 7000 & consumption < 8000) = {'high'};
NewColumn(consumption >= 8000) = {'Forest Fire'};
Only you can prevent Forest Fires.

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

추가 답변 (0개)

카테고리

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