Info

此问题已关闭。 请重新打开它进行编辑或回答。

Index exceeds matrix problem

1 次查看(过去 30 天)
Gokhan Kayan
Gokhan Kayan 2018-1-25
关闭: MATLAB Answer Bot 2021-8-20
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 个评论
Gokhan Kayan
Gokhan Kayan 2018-1-30
Thanks for your reply dpb I solved it with different method :)

回答(2 个)

dpb
dpb 2018-1-25
编辑:dpb 2018-1-26
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.

Jan
Jan 2018-1-30
编辑:Jan 2018-1-30
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

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by