Replacing values based on a condition in a matrix.

20 次查看(过去 30 天)
Hi there!
I have a 2by2 matrix and am trying to replace every value in the second matrix that is greater than 20 with "on".
So basically I want something like this:
1 2
2 30
30 50
40 10
55 15
to change to this:
1 closed
2 open
30 open
40 closed
55 closed
If anyone can help that would be great! Thanks!

回答(1 个)

Kevin Phung
Kevin Phung 2019-3-20
编辑:Kevin Phung 2019-3-20
%let M be your matrix;
ind = M(:,2) > 20; %grab indices along second column where value is > 20
M = num2cell(M); % youre going to need to turn it into a cell array
M(ind,2) = {'open'}; %set those indices to open
M(~ind,2) = {'closed'}; %set indices that are not to closed
M
let me know if this helps. Also, I suggest you read about cell arrays:
  3 个评论
Kevin Phung
Kevin Phung 2019-3-20
Happy to help!
As for adding titles to the column, Walter's comment would work.
Another option is to turn the cell matrix into a table:
ind = M(:,2) > 20; %grab indices along second column where value is > 20
M = num2cell(M); % youre going to need to turn it into a cell array
M(ind,2) = {'open'}; %set those indices to open
M(~ind,2) = {'closed'}; %set indices that are not to closed
M = table(M(:,1),M(:,2),'VariableNames',{'Name1','Name2'})

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by