match values of cells to numbers
2 views (last 30 days)
Show older comments
Hello,
I have the following cell
cell =
6×6 cell array
{' A'} {'B' } {0×0 double} {0×0 double} {0×0 double} {0×0 double}
{' A'} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double}
{' A'} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double}
{' A'} {0×0 double} {0×0 double} {0×0 double} {0×0 double} {0×0 double}
{' A'} {'D' } {0×0 double} {0×0 double} {0×0 double} {0×0 double}
{' A'} {'B' } {'C' } {0×0 double} {0×0 double} {0×0 double}
The characters 'A', 'B, 'C' and 'D' and 'E' are stored in a cell called name
name =
5×1 cell array
{'A'}
{'B'}
{'C'}
{'D'}
{'E'}
And to each letter, A, B, C , D and E I assign a number, 1 for A, 2 for B, 3 for C , 4 for D and 5 for E. I would like to create a matrix such as
mat =
1 2 0 0 0 0
1 0 0 0 0 0
1 0 0 0 0 0
0 0 0 0 0 0
1 4 0 0 0 0
1 2 3 0 0 0
So far what I do is use strfind for each value of cell to see if it finds name{1}, name{2}, name{3} etc
for i=1:6
for j=1:6
for k=1:5
idk1=strfind(cell{i,j},name{k});
if isempty(idk1)
mat(i,j,k)=0;
else
mat(i,j,k)=idk1;
end
end
end
end
result=zeros(6,6);
for i=1:KK
result(logical(ire(:,:,i)))=i;
end
Is there a simpler way to do this? This is just an exemple but I'll have cells with over 1000 rows and columns and I'd like to avoid checking each value individually.
Thanks!
0 Comments
Accepted Answer
Stephen23
on 23 Jan 2019
Edited: Stephen23
on 23 Jan 2019
% Fake data:
C = cell(6,6);
C(:,1) = {'A'};
C([1,6],2) = {'B'};
C(6,3) = {'C'};
C(5,2) = {'D'};
V = {'A','B','C','D','E'};
% Use ISMEMBER:
X = cellfun(@ischar,C);
M = zeros(size(C));
[~,Z] = ismember(C(X),V)
M(X) = Z
Which gives:
M =
1 2 0 0 0 0
1 0 0 0 0 0
1 0 0 0 0 0
1 0 0 0 0 0
1 4 0 0 0 0
1 2 3 0 0 0
More Answers (0)
See Also
Categories
Find more on Logical 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!