Organize matrix data into Bins using loop

조회 수: 1 (최근 30일)
Ben Whitby
Ben Whitby 2022년 7월 19일
댓글: Ben Whitby 2022년 7월 20일
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.

채택된 답변

Stephen23
Stephen23 2022년 7월 19일
편집: Stephen23 2022년 7월 19일
"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
Stephen23
Stephen23 2022년 7월 19일
편집: Stephen23 2022년 7월 19일
"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 2022년 7월 20일
Thanks, The accumarray works well.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by