australopithecus
australopithecus

Reputation: 69

Changing cell values in matlab

I have a variable in matlab as 101x2 cell array and I need to recode the strings for my analysis.

for example I want to change {'red apple'} to {'blue banana'} with checking all red apple cells.

I tried something like this;

A.mycell(cell2mat(cellfun(@(elem) elem == 'red apple', A.mycell(:, :), 
'UniformOutput', true))) = {'blue banana'};

but this did not work, how can I change something like this?

also this didn't work too;

ind= find(A.mycell=={'red apple'})
A.mycell(ind)= 'blue banana'

Upvotes: 0

Views: 115

Answers (1)

natemcintosh
natemcintosh

Reputation: 880

Matlab's strcmp function is useful in cases like this. Another key thing to note here is you can access the string inside a cell element by with myCellArray{row, col}. Using myCellArray(row, col) will give you a cell with a string inside it.

clc; clear;

myCellArray = {'red apple'   , 'green pear'   ;...
               'green pear'  , 'red apple'    ;...
               'red apple'   , 'red pineapple';...
               'orange lemon', 'red apple'}   ;
keyword = 'red apple';
for row = 1:size(myCellArray,1)
    for col = 1:size(myCellArray,2)
        if strcmp(keyword, myCellArray{row,col})
            myCellArray{row,col} = 'blue banana';
        end
    end
end
myCellArray

Which outputs

myCellArray =

  4×2 cell array

{'blue banana' }    {'green pear'   }
{'green pear'  }    {'blue banana'  }
{'blue banana' }    {'red pineapple'}
{'orange lemon'}    {'blue banana'  }

Upvotes: 1

Related Questions