フィルターのクリア

how to efficiently encode two values as a unique entitiy

2 ビュー (過去 30 日間)
balandong
balandong 2018 年 11 月 23 日
編集済み: Jan 2018 年 11 月 26 日
Dear all,
With respect to the above subject, I wonder if we can make the following code more efficient and compact (reduce the ifelse)..
A=3;
B=3;
C=[];
if A==1 && B==1
C=1;
elseif A==1 && B==2
C=2;
elseif A==1 && B==3
C=3;
elseif A==2 && B==2
C=4;
elseif A==2 && B==3
C=5;
elseif A==3 && B==1
C=6;
elseif A==3 && B==2
C=7;
elseif A==3 && B==3
C=8;
end
In addition, I also wonder if we can scale it up for A=[2;2;3;1] and B= [1;1;3;1]
Thanks in advance

採用された回答

Jan
Jan 2018 年 11 月 23 日
編集済み: Jan 2018 年 11 月 26 日
A = 3;
B = 3;
Q = [1, 1, 1, 2, 2, 3, 3, 3; ... % A
1, 2, 3, 2, 3, 1, 2, 3; ... % B
1, 2, 3, 4, 5, 6, 7, 8].'; % C
idx = ismember(Q(:, 1:2), [A, B], 'rows');
C = Q(idx, 3);
I do not know what " scale it up for A=[2;2;3;1] and B= [1;1;3;1]" means.

その他の回答 (1 件)

Jan
Jan 2018 年 11 月 23 日
編集済み: Jan 2018 年 11 月 23 日
Start with a simplification by omitting repeated comparisons:
A = 3;
B = 3;
C = [];
if A == 1
if B == 1
C = 1;
elseif B == 2
C = 2;
elseif B == 3
C = 3;
end
elseif A == 2
if B == 2
C = 4;
elseif B == 3
C = 5;
end
elseif A == 3
if B == 1
C = 6;
elseif B == 2
C = 7;
elseif B == 3
C = 8;
end
end
This should run faster, but is not much nicer. What about switch ?
A = 3;
B = 3;
C = [];
switch A
case 1
switch B
case 1
C = 1;
case 2
C = 2;
case 3
C = 3;
end
case 2
switch B
case 2
C = 4;
case 3
C = 5;
end
case 3
switch B
case 1
C = 6;
case 2
C = 7;
case 3
C = 8;
end
end
end
Nope, not nicer also.

カテゴリ

Help Center および File ExchangeTime Series Objects についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by