using find function and stor the filtered data in a Matrix

Hello,
I have two columns of data. frequency and H. Now I want to find H values, which the respective frequency values belongs to predefined classess and stor them in a matrix. per say, f = (1.3; 1.4; 2.1; 2.5; 2.7; 2.8; 3.4) and H = (5;6;7;3;2;4;9). Now I want to find which H values falls in frequency classes of (1-2), (2-3), (3-4) and store them in a matrix (may be row sizes are unequal, make it equal size with rest of the elements being set to zeros). Since I have so many classes, I am hoping to do so using a for loop and find function. (expected answer is something like below with columns are representing frequency classes of (1-2), (2-3), (3-4) in order.
[5 7 9
6 3 0
0 2 0
0 4 0]

 採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 2 月 23 日
編集済み: Dyuman Joshi 2023 年 2 月 24 日

1 投票

Assuming the ranges are [1,2), [2,3) ...
f = [1.3; 1.4; 2.1; 2.5; 2.7; 2.8; 3.4];
H = [5;6;7;3;2;4;9];
arr = floor(f);
[~,m]=mode(arr);
%pre-allocation
out = zeros(m,max(arr));
%generalised approach instead of 1:max(arr)
for k = unique(arr)'
z = arr==k;
out(1:nnz(z),k)=H(z);
end
out
out = 4×3
5 7 9 6 3 0 0 2 0 0 4 0

3 件のコメント

Voss
Voss 2023 年 2 月 24 日
Note that using mode(arr) for determining the number of rows to pre-allocate in the output matrix is not correct in general; it should be nnz(arr==mode(arr)) to get the number of times the mode of arr appears in arr, rather than just the mode of arr itself.
Dyuman Joshi
Dyuman Joshi 2023 年 2 月 24 日
Thanks for pointing it out, Voss. I have edited my code to rectify the mistake.
Tharindu
Tharindu 2023 年 2 月 24 日
Thanks Joshi and Voss! I figured out the logic behind. Great help. Thanks to both of you!!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

質問済み:

2023 年 2 月 22 日

コメント済み:

2023 年 2 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by