Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Index exceeds matrix problem

1 vue (au cours des 30 derniers jours)
Gokhan Kayan le 25 Jan 2018
Clôturé : MATLAB Answer Bot le 20 Août 2021
I have a cell array (7879x1)and I want to create a new character array that depends on this cell array. For example my first 5 character array is:
KA
KT
Zb2.Cd4t1R2
Zb2.Bd4t1R2
Zb2.Ard4t1R1
Zb2.Bd4t2R2
I write a code to form new cell array called 'Group':
for i=1:numel(cell);
if cell{i}(3)==1;
Group{i}='A';
else if cell{i}(3)== 2;
Group{i}= 'A';
else if cell{i}(3)== 3;
Group{i}= 'A';
else if cell{i}(3)== 4;
Group{i}= 'B';
else if cell{i}(3)== 5;
Group{i}= 'D';
else if cell{i}(3)== 6;
Group{i}= 'D';
end
end
end
end
end
end
end
but since I haven't got any value for cell{1}(3) and cell{2}(3). it gives me error. How can I solve the problem and How can I say that if cell{i} (3) has no value it should be zero. I try
else if cell{i}(3)== ''; Group{i}= '0',
but it doesn't work.
2 commentairesAfficher AucuneMasquer Aucune
Gokhan Kayan le 30 Jan 2018
Thanks for your reply dpb I solved it with different method :)
dpb le 30 Jan 2018
So, show us! :)

Réponses (2)

dpb le 25 Jan 2018
Modifié(e) : dpb le 26 Jan 2018
In brute force, use try ... catch ... end to catch the error elements
for i=1:length(cell)
try
if cell{i}(3)==1;
...
catch % if err on indexing, end up here
Group{i}= '0',
end
end
But the code as given just begs for alternate implementations...at a bare minimum use a SWITCH construct something like
for i=1:length(cell)
try
c=cell{i}(3) % pick the wanted character
switch(c)
case {1, 2, 3}
Group{i}= 'A';
case {4}
Group{i}= 'A';
case {5, 6}
Group{i}= 'D';
...
else
....
end % switch construct
catch % if err on indexing, end up here
Group{i}= '0',
end % try...catch block
end % for...end block
but even that needs a lot of code and editing. I'm out of time, maybe somebody else will come along and illustrate the use of a "lookup table" with which you could vectorize it and make the case definitions exist in just a data table/array.
0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Jan le 30 Jan 2018
Modifié(e) : Jan le 30 Jan 2018
Data = {'KA', ...
'KT', ...
'Zb2.Cd4t1R2', ...
'Zb2.Bd4t1R2', ...
'Zb2.Ard4t1R1', ...
'Zb2.Bd4t2R2'};
Pool = 'AAABDD';
Group = cell(1, length(Data)); % Pre-allocate
Group(:) = {'0'};
for iData = 1:length(Data)
S = Data{iData};
if length(S) > 2
Group{iData} = Pool(S(3) - '0');
end
end
0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by