Info
この質問は閉じられています。 編集または回答するには再度開いてください。
Index exceeds matrix problem
1 回表示 (過去 30 日間)
古いコメントを表示
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 件)
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.
0 件のコメント
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
0 件のコメント
この質問は閉じられています。
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!