[A,I] = histc([0.9828 0.4662 0.5245 0.9334 0.2163],[0.0191 0.2057 0.2820 0.2851 1.0000])
这是带有结果的MATLAB代码:
A =
0 1 0 4 0
I =
4 4 4 4 2
我需要的是我。我尝试过使用np.histogram,但它给了我这个:
>>> a,b = np.histogram([0.9828 , 0.4662 , 0.5245 , 0.9334 , 0.2163],[0.0191 , 0.2057 , 0.2820 , 0.2851 , 1.0000])
>>> a
array([0, 1, 0, 4])
>>> b
array([ 0.0191, 0.2057, 0.282 , 0.2851, 1. ])
我想得到数组/矩阵中每个元素都进入的bin。
答案 0 :(得分:7)
您要找的是numpy.digitize
:
返回输入数组中每个值所属的bin的索引。
>>> a = np.digitize([0.9828 , 0.4662 , 0.5245 , 0.9334 , 0.2163],[0.0191 , 0.2057 , 0.2820 , 0.2851 , 1.0000])
>>> print(a)
[4 4 4 4 2]
答案 1 :(得分:1)
以下是matlab的histc的正确python实现:
import { AbstractControl } from '@angular/forms';
import { Observable, Observer, of } from 'rxjs';
export const mimeType = (
control: AbstractControl
): Promise<{ [key: string]: any }> | Observable<{ [key: string]: any }> => {
if (!control.value || typeof(control.value) === 'string') { return of(null); }
const file = control.value as File;
const fileReader = new FileReader();
const frObs = Observable.create(
(observer: Observer<{ [key: string]: any }>) => {
fileReader.addEventListener('loadend', () => {
const arr = new Uint8Array(fileReader.result as ArrayBuffer ).subarray(0, 4);
let header = '';
let isValid = false;
for (let i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
switch (header) {
case '89504e47':
isValid = true;
break;
case 'ffd8ffe0':
case 'ffd8ffe1':
case 'ffd8ffe2':
case 'ffd8ffe3':
case 'ffd8ffe8':
isValid = true;
break;
case '25504446':
isValid = true;
break;
default:
isValid = false; // Or you can use the blob.type as fallback
break;
}
if (isValid) {
observer.next(null);
} else {
observer.next({ invalidMimeType: true });
}
observer.complete();
});
fileReader.readAsArrayBuffer(file);
}
);
return frObs;
};
答案 2 :(得分:0)
numpy.digitize不是Matlab histc的完整复制品。这有效:
import numpy as np
def histc(X, bins):
map_to_bins = np.digitize(X,bins)
r = np.zeros(bins.shape)
for i in map_to_bins:
r[i-1] += 1
return [r, map_to_bins]
if __name__=="__main__":
X = np.array([0.9828, 0.4662, 0.5245, 0.9334, 0.2163])
bins = np.array([0.0191, 0.2057, 0.2820, 0.2851, 1.0])
[A,I] = histc(X, bins)
print("X", X)
print("bins", bins)
print("A",A,"expecting", [0, 1, 0, 4, 0])
print("I",I,"expecting", [4, 4, 4, 4, 2])
答案 3 :(得分:0)
在python中正确实现MATLAB histc函数(source)。
def histc(x, bins):
map_to_bins = np.digitize(x, bins) # Get indices of the bins to which each value in input array belongs.
res = np.zeros(bins.shape)
for el in map_to_bins:
res[el-1] += 1 # Increment appropriate bin.
return res