필터 지우기
필터 지우기

how to seek and replace characters on cell

조회 수: 4 (최근 30일)
vx2008
vx2008 2015년 11월 27일
댓글: Geoff Hayes 2015년 11월 28일
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.

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 11월 27일
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
vx2008
vx2008 2015년 11월 28일
편집: Geoff Hayes 2015년 11월 28일
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 2015년 11월 28일
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);

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

추가 답변 (1개)

Stephen23
Stephen23 2015년 11월 27일
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)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by