[英]How to do following in Matlab?
假設我有n
數字的序列
e=[5,4,45,63,22,22,1,12,3,2,2,16,14,14,16,17,1,19,21,15,32,32,27,27,43,41,7,8,13,23,23]
然后是前10
數字,即
[5,4,45,63,22,22,1,12,3,2]
計算除1
到5
之外的數字,然后除以10
,即
[45,63,22,22,12]
總共5
,所以結果應該是5/10
,現在是前20
數字,即
[5,4,45,63,22,22,1,12,3,2,2,16,14,14,16,17,1,19,21,15]
然后
[45,63,22,22,12,16,14,14,16,17,19,21,15]
總= 13
,所以13/20
,像這樣對10
, 20
, 30
,...直至n
數字,然后情節數字與x
軸上的點0
10
20
30
... n
和y
與軸5/10
, 13/20
,...如何執行此操作
我嘗試過
for e=10:10:400
for u=1:length(e)
d=(numel(u)>5)
h=d/u
end
end
但顯示出不同。
嘗試這個
e= [5,4,45,63,22,22,1,12,3,2,2,16,14,14,16,17,1,19,21,15,32,32,27,27,43,41,7,8,13,23,23];
bins = 10:10:numel(e);
counts = NaN(1,numel(bins)); %// pre-allocation. I'm pre-allocating with NaN here instead of zeros because 0 is a valid result for an element of counts and thus could make us miss errors should something go wrong
for k = 1:numel(bins)
counts(k) = sum(e(1:bins(k)) > 5)/bins(k);
end
plot(bins, counts) %// or you might prefer bar(bins, counts)
這里e(1:bins(k))
將是循環的第一次迭代中e
的前10
元素,第二次迭代中的前20
個,依此類推。 sum(... > 10)
僅計算有多少個元素大於5
。 要了解其工作原理,請考慮x = [3 4 5 6 7 8 5 1 2]
。 現在x > 5
將返回邏輯數組[0 0 0 1 1 1 0 0 0]
,所以sum(x>10)
與sum([0 0 0 1 1 1 0 0 0])
,即3
x
大於5
的元素數。 現在,你只需要在不同的元素來存儲該計數counts
在每一次迭代,因此我們有counts(k) = ...
而不是counts = ...
因為后者(即你的代碼是如何擁有它)只是覆蓋counts
與每次迭代的標量計數,而不是創建一個向量來記錄每次迭代的每個計數。
在MATLAB中,您通常可以取消循環,在這種情況下也可以這樣做:
counts = cumsum(e > 5)./(1:numel(e));
h = counts(10:10:end);
希望這可以幫到你
n=30 % this because of the 'e' size
Lim = 5 % your limit
Steps = 10 %
xValues = Steps:Steps:n
PlotSeries = NaN(size(e,2)/Steps,2)
for x = 1:1:size(e,2)/Steps
PlotSeries(x,:) = [xValues(x),size(e(e(1:xValues(x))>Lim),2)/xValues(x)]
end
plot(PlotSeries)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.