Replacing values in a cell which is part of matrix

6 Ansichten (letzte 30 Tage)
Aleksandar
Aleksandar am 22 Mär. 2015
Kommentiert: Guillaume am 23 Mär. 2015
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

Akzeptierte Antwort

Guillaume
Guillaume am 22 Mär. 2015
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 Kommentar
Guillaume
Guillaume am 23 Mär. 2015
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}.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Aleksandar
Aleksandar am 22 Mär. 2015
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?

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by