Organize matrix data into Bins using loop

5 次查看(过去 30 天)
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by