problem to write a condition for 'if'

조회 수: 6 (최근 30일)
NA
NA 2020년 3월 26일
답변: Birdman 2020년 3월 26일
I want to save A_new according to this condition:
If A_new decreases the length of B, I want to save it.
I wrote a code like this but I have a problem to write a condition
A = {[1,2,3,4], [1,2,3,6], [1,2,3,8], [1,2,6,7,8], [1,6,8], [2,3,4,7], [3,4,6], [3,4,6,7], [3,4,6,7,8], [3,6,8], [6,7,8], [1,5]};
B =[1 2; 1 4; 1 8; 1 5; 1 6; 2 7; 2 3; 3 6; 3 8; 3 4; 4 7; 4 6; 7 6; 7 8; 6 8];
B_bk = B;
A_new = cell([],1);
length_B = cell([],1);
%% sort A
[~,I] = sort(cellfun(@length,A));
A = A(I);
C = [];
if isempty(B)==0
for i=1:length(A)
temp = [A{i} A{i}(1)];
C = [C;[temp(1:end-1)' temp(2:end)']];
[~,X] = setdiff(sort(B_bk,2),sort(C,2),'rows','stable');
B = B_bk(X,:);
length_B{i} = length(B);
%% problem to write condition
if length_B{i}- length_B{i-1}>0 %%???
A_new{i} = A{i};
end
end
end
result should be
A_new = {[1,5],[1,6,8],[3,4,6],[3,6,8],[6,7,8],[1,2,3,4],[2,3,4,7]};
I think it would be better way to write this code.

채택된 답변

Birdman
Birdman 2020년 3월 26일
Try the following code:
A = {[1,2,3,4], [1,2,3,6], [1,2,3,8], [1,2,6,7,8], [1,6,8], [2,3,4,7], [3,4,6], [3,4,6,7], [3,4,6,7,8], [3,6,8], [6,7,8], [1,5]};
B =[1 2; 1 4; 1 8; 1 5; 1 6; 2 7; 2 3; 3 6; 3 8; 3 4; 4 7; 4 6; 7 6; 7 8; 6 8];
B_bk = B;
A_new = cell([],1);
length_B = cell([],1);
%% sort A
[~,I] = sort(cellfun(@length,A));
A = A(I);
C = [];
for i=1:length(A)
temp = [A{i} A{i}(1)];
C = [C;[temp(1:end-1)' temp(2:end)']];
[~,X] = setdiff(sort(B_bk,2),sort(C,2),'rows','stable');
B = B_bk(X,:);
length_B{i} = length(B);
if i==1
A_new{i} = A{i};
end
%% problem to write condition
if i>1
if length_B{i-1}- length_B{i}>0 %%???
A_new{i} = A{i};
end
end
end
A_new=A_new(~cellfun(@isempty,A_new))

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Signal Generation, Analysis, and Preprocessing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by