how to seek and replace characters on cell

4 views (last 30 days)
Now I have a mat A as below:
A=[1 1 1;1 2 2;2 1 2;2 2 1]
A =
1 1 1
1 2 2
2 1 2
2 2 1
Now want to replace '1' and '2' with 'a' and 'b' seperately; so I use function 'mat2cell()' to set mat A as cell B; but I don't know how shall I do the above replacement.

Accepted Answer

Geoff Hayes
Geoff Hayes on 27 Nov 2015
Rather than converting the matrix to a cell array using mat2cell, consider applying a function to each element of A using arrayfun. Define a mapping for 1 and 2 and apply that mapping to each element. For example,
map = {'a', 'b'};
We will treat the elements of A as indices into the map as
B = arrayfun(@(x)map(x),A);
where
B =
'a' 'a' 'a'
'a' 'b' 'b'
'b' 'a' 'b'
'b' 'b' 'a'
  6 Comments
vx2008
vx2008 on 28 Nov 2015
Edited: Geoff Hayes on 28 Nov 2015
Thank you again. I have get it according to your guiding.
About the code data = mat2cell(data,ones(1,size(data,1)),ones(1,size(data,2))), it can be instead by data=num2cell(data).
Now I have get the data as below:
data
data =
'45 ℃' '2.2g' '5.0kg' [ 46]
'45 ℃' '3.0g' '7.0kg' [ 53]
'55 ℃' '2.2g' '7.0kg' [ 60]
'55 ℃' '3.0g' '5.0kg' [ 50]
[ 99] [ 106] [ 96] [ 0]
[ 110] [ 103] [ 113] [ 0]
[ 13.4444] [ 1] [ 32.1111] [ 0]
[161.4476] [4.0522e+03] [1.6211e+04] [2.2500]
then I run the code as below:
f=figure('Position',[0 60 120+C*80,30+R*20]);
t=uitable(f,'Data',data{:},'ColumnName',cname,'RowName',rname);
Then the Matlab complained that:
Error using cell/strmatch (line 19)
Requires character array or cell array of strings as inputs.
Error in uitable_parseold (line 41)
if (~isempty(strmatch(lower(args{index}),
oldpropnames, 'exact')))
Error in uitable (line 40)
if (nargout == 2) ||(uitable_parseold(varargin{:}))
so maybe I still should make some modification about it. I think I should convert all number's cells of data into character cells; and then convert data matrix into 1X1 matrix. but I don't know how?
Geoff Hayes
Geoff Hayes on 28 Nov 2015
If you want to convert each element of the cell array to a string, then use cellfun to apply num2str to convert each number. For example, try
dataStr = cellfun(@(k)num2str(k),data,'UniformOutput',false);

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 27 Nov 2015
There is no need to use complicated arrayfun, simply use A as an index:
>> A = [1 1 1;1 2 2;2 1 2;2 2 1];
>> map = {'a','b'};
>> B = map(A)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!