필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How to fix this loop?

조회 수: 1 (최근 30일)
Aswin Sandirakumaran
Aswin Sandirakumaran 2018년 6월 30일
마감: MATLAB Answer Bot 2021년 8월 20일
C = {1,2,3,1,4,6};
%for i = 1:length(C)
List = cell(size(C)); %creating empty list
for i = 1:length(C)
if isequal(C{i}, 1)
List(1) = C(i);
else
List(2) = C(i);
end
end
I GET A OUTPUT OF LIST AS =
BUT MY OUTPUT SHOULD LOOK LIKE:
IN cell 1 = [1,1]
IN CELL 2 = [2,3,4,6]
THE PROBLEM IS IT STORES THE LAST ELEMENT ENCOUNTERED , BUT IT SHOULD STORE ALL ELEMENTS ENCOUNTERED. HOW TO FIX THIS??

답변 (1개)

Stephen23
Stephen23 2018년 6월 30일
편집: Stephen23 2018년 6월 30일
Simpler with a numeric vector:
>> V = [1,2,3,1,4,6];
>> List = {V(V==1),V(V~=1)};
>> List{1}
ans =
1 1
>> List{2}
ans =
2 3 4 6
Note: to get V from the cell array C:
V = [C{:}];
But if you really want to write inefficient code using a loop:
List = cell(1,2);
for k = 1:numel(C)
if isequal(C{k}, 1)
List{1} = [List{1},C{k}];
else
List{2} = [List{2},C{k}];
end
end
which produces exactly the same output less efficiently using more lines of code.
  댓글 수: 1
Stephen23
Stephen23 2018년 6월 30일
편집: Stephen23 2018년 6월 30일
Try this:
C = {1,2,3,1,4,6};
List = cell(1,2);
for k = 1:numel(C)
if isequal(C{k}, 1)
List{1} = [List{1},C{k}];
else
List{2} = [List{2},C{k}];
end
end
giving
>> List{1}
ans =
1 1
>> List{2}
ans =
2 3 4 6

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by