Organize matrix data into Bins using loop

1 visualizzazione (ultimi 30 giorni)
Hi All,
I have some time series data in a matix, called NorthBlindChSpeed1. What I want to do is organise that data into evenly spaced Bins. The code I have so far, whcih works, is as shown below
NorthBlindChSpeed1 = [0.2; 0.4; 0.8; 0.8; 1; 1.19; 0.3; 1.41; 1.47; 1.51];
B1 =(NorthBlindChSpeed1(:, 1)< 0.2 & NorthBlindChSpeed1(:,1)>= 0);
B2 =(NorthBlindChSpeed1(:, 1)< 0.4 & NorthBlindChSpeed1(:,1)>= 0.2);
B3 =(NorthBlindChSpeed1(:, 1)< 0.6 & NorthBlindChSpeed1(:,1)>= 0.4);
B4 =(NorthBlindChSpeed1(:, 1)< 0.8 & NorthBlindChSpeed1(:,1)>= 0.6);
B5 =(NorthBlindChSpeed1(:, 1)< 1.0 & NorthBlindChSpeed1(:,1)>= 0.8);
B6 =(NorthBlindChSpeed1(:, 1)< 1.2 & NorthBlindChSpeed1(:,1)>= 1.0);
B7 =(NorthBlindChSpeed1(:, 1)< 1.4 & NorthBlindChSpeed1(:,1)>= 1.2);
B8 =(NorthBlindChSpeed1(:, 1)< 1.6 & NorthBlindChSpeed1(:,1)>= 1.4);
This code works and it assigns the values in the Matrix NorthBlindChSpeed1 into the appropriate bins. The trouble with this code is that one has to manually assign the data to each Bin. For the real data set I will require 250 Bins... Is there a more efficient way to Bin this data??? Perhaps using a For Loop.
I appreciate your help.

Risposta accettata

Stephen23
Stephen23 il 19 Lug 2022
Modificato: Stephen23 il 19 Lug 2022
"Is there a more efficient way to Bin this data???"
Using inbuilt functions will be the most efficient approach, e.g. DISCRETIZE or HISTCOUNTS:
V = [0.2; 0.4; 0.8; 0.8; 1; 1.19; 0.3; 1.41; 1.47; 1.51];
E = 0:0.2:1.6; % bin edges
idy = discretize(V,E)
idy = 10×1
2 3 5 5 6 6 2 8 8 8
[cnt,~,idx] = histcounts(V,E)
cnt = 1×8
0 2 1 0 2 2 0 3
idx = 10×1
2 3 5 5 6 6 2 8 8 8
These will be much better approaches than copy-and-pasting lines of code, using loops, or numbering variable names.
  3 Commenti
Stephen23
Stephen23 il 19 Lug 2022
Modificato: Stephen23 il 19 Lug 2022
"It's not clear how I would do that using the binning method you have proposed."
Using arrays, because this is MATLAB. Forget about writing out lots of numbered variable names like that, that is a dead-end. And copy-and-pasting lines of code is just doing the computer's job for it, best avoided.
You should use ACCUMARRAY or perhaps GROUPSUMMARY or something similar:
V = [0.2; 0.4; 0.8; 0.8; 1; 1.19; 0.3; 1.41; 1.47; 1.51];
P = rand(1,numel(V)); % corresponding power values
E = 0:0.2:1.6; % bin edges
[cnt,~,idx] = histcounts(V,E);
A = accumarray(idx,P(:),[8,1],@sum)
A = 8×1
0 0.8271 0.6048 0 1.2723 1.6261 0 1.8971
B = zeros(8,1);
B(cnt>0) = groupsummary(P(:),idx,@sum)
B = 8×1
0 0.8271 0.6048 0 1.2723 1.6261 0 1.8971
Ben Whitby
Ben Whitby il 20 Lug 2022
Thanks, The accumarray works well.

Accedi per commentare.

Più risposte (0)

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by