Replacing values in a cell which is part of matrix

조회 수: 3 (최근 30일)
Aleksandar
Aleksandar 2015년 3월 22일
댓글: Guillaume 2015년 3월 23일
I have a cell column, which is a third column of a matrix named 'a'. The cell column contains values A,B,C,D and E. I just want to change all E's to D. Unfortunately this does not work with cells: a(a=='E')='D'; (I am aware that if I cell2mat the column the above will work, but I have to keep it in a cell format.) I suppose it can be done somehow with cellfun ...but how??? Regards

채택된 답변

Guillaume
Guillaume 2015년 3월 22일
I have to keep it in a cell format
Why? If it's a cell array of scalar, a matrix is a lot more efficient.
There are several ways to do this.
1) convert to matrix, replace and convert back to cell array:
tmp = cell2mat(a);
tmp(tmp == E) == D;
a = num2cell(tmp)
2) use cellfun:
a(cellfun(@(elem) elem == E, a)) = {D}
  댓글 수: 1
Guillaume
Guillaume 2015년 3월 23일
Aleksandar comment as an answer copied here: Guillaume, thank you, just a couple a few clarifications please. with this I can change the tmp
tmp = cell2mat(a(:,3)); %I take the third column
tmp(tmp=='E')='D';
tmp = num2cell(tmp);
Now the tmp column contains only A, B, C and D, and is still in a cell format. But how should I now revert it in my matrix 'a' (it was a third column)? As I want to use 'a' matrix in transprob function. (The first and second column are other information (such as ID and date).). PS the cellfun example is not clear to me?
Sorry, I missed that a was the whole cell array, not just the column, the proper code would be:
tmp = cell2mat(a(:, 3));
tmp(tmp == E) == D;
a(:, 3) = num2cell(tmp); %put it back where it came from
And with cellfun:
a(cellfun(@(elem) elem == E, a(:, 3)), 3) = {D}
What the cellfun does is go over each element of the cell array passed to it (in this latter case a(:, 3)) and pass it to the anonymous function:
@(elem) elem == E
This function takes one argument elem, and compare it to E. Therefore it returns a boolean true (1) of false (0). Thus the result of the cellfun is a logical array which tells you which row of a to replace with {D}.

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

추가 답변 (1개)

Aleksandar
Aleksandar 2015년 3월 22일
Guillaume, thank you, just a couple a few clarifications please
with this I can change the tmp
tmp = cell2mat(a(:,3)); %I take the third column; tmp(tmp=='E')='D'; tmp = num2cell(tmp); Now the tmp column contains only A, B, C and D, and is still in a cell format. But how should I now revert it in my matrix 'a' (it was a third column)? As I want to use 'a' matrix in transprob function. (The first and second column are other information (such as ID and date).)
PS the cellfun example is not clear to me?

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by