Compare elements of an array with all elements in a matrix

1 回表示 (過去 30 日間)
Arlinda Gashi
Arlinda Gashi 2021 年 7 月 27 日
コメント済み: KSSV 2021 年 7 月 27 日
I have a matrix P (18x10), and one array C (1x10). I want to compare each element of C with each element of each row in P (see if elements in C are bigger than elements in P).
(As an illustration, I want to see if: C(1)> P(1,1); C(1)> P(1,2); ... C(2)>P(2,1); C(2)>P(2,2)...).
P = randn(18,10);
C = randn(1,10);
I tried to do this as follows:
for a = 1:length(C)
for m = 1:size(P,2)
for m_row = 1:size(P,1)
logvec= length(C(a))>P(m_row, m:end);
end
end
end
I get the following error: Unable to perform assignment because the left and right sides have a different number of elements.
I expect as an output a matrix 18x10, with 0s and 1s.
I'd appreciate your help! Thank you!

採用された回答

KSSV
KSSV 2021 年 7 月 27 日
No loop needed. You can use straight away like shown:
P = randn(18,10);
C = randn(1,10);
C1 = repmat(C,18,1) ;
idx = C1 > P
  3 件のコメント
Arlinda Gashi
Arlinda Gashi 2021 年 7 月 27 日
This just made my life way easier :) !
Thanks a lot!
KSSV
KSSV 2021 年 7 月 27 日
@Chunru yes you are right. It is redundant. Can be removed.

サインインしてコメントする。

その他の回答 (1 件)

Chunru
Chunru 2021 年 7 月 27 日
P = randn(5,4)
P = 5×4
0.4430 1.0634 -0.8297 -0.4101 -1.1517 -2.1151 1.2150 0.3174 1.2722 1.9258 -2.0465 -0.1428 0.2521 1.2782 -0.3429 -0.4121 0.4291 0.8109 -1.9595 -0.0784
C = randn(1,4)
C = 1×4
1.3790 -1.2752 -0.2469 -0.1746
lv = C > P
lv = 5×4 logical array
1 0 1 1 1 1 0 0 1 0 1 0 1 0 1 1 1 0 1 0

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by