2017-07-24 25 views
-1

希望我不會咀嚼這個問題,但我正在尋找一種更有效的方式來完成這個小任務在MATLAB中完成。基本上,我有一個具有相應值的年份列表,其中年份重複。例如:更有效的方式來有條件地保持矩陣的某些行

...

1910 1.04

1910 2.53

1910 0.94

1911年2.13

1911年5.32

...

我想選擇一個年份範圍,並取所有範圍內col2中所有值的平均值。我現在這樣做的方式是創建一個邏輯數組max_year> = data(:,1)> = min_year,並將此數組與數據(:,2)連接起來(例如new_data = horzcat(logical_array,data(:,2 ))),使用「find」標記這個數組的索引是0還是1,然後如果是1,則將數據從數據拖到data2,如果是0,則完全刪除該行。

這是代碼的樣子

years = rawdata(:,yearcolumn);    %extracts year vector from data 
years = years>=firstyear_i&years<maxyear; %labels which rows we are considering 
levels = [years,rawdata(:,datacolumn)]; %new vector where first column shows if being considered and second is rawdata for that row 
indices1 = find(levels(:,1)==0);   %indexes rows for deletion 
indices2 = find(levels(:,1)==1);   %indexes rows we are using 
levels(indices2,1) = rawdata(indices2,1); %if using row, replace "1" with appropriate year from rawdata 
levels(indices1,:) = [];     %if not using row, remove it from data we are considering 

我想知道是否有更好的方式來做到這兩種。謝謝!

回答

0

那裏有幾個太多的步驟。只需使用你想要的並取平均值的索引。像這樣:

values = [1910 1.04;1910 2.53;1910 0.94;1911 2.13;1911 5.32]; 
index = values(:,1) == 1910; 
av = mean(values(index, 2)); 

對於這種情況av = 1.503333333333

爲了節省只是東西(而不是稍後刪除所有內容),請執行此操作。

stuffToKeep = values(index,:); 
stuffToKeep = values(values(:,1) == 1910,:); % 1-liner if you don't want to save the index 

如果您想保留信息後,只需保存索引,當你需要它記得它。

years = unique(values(:,1)); 
% then find all the values that match each year 
[~, yearIndex] = ismember(values(:,1), years); 
% use the index 
mean(values(yearIndex == 1,2)); % same as before average of 1910 
mean(values(yearIndex == 2,2)); % average of 1911 

什麼範圍?同樣的邏輯。

index = values(:,1) >= 1910 & values(:,1) <= 1920; 
mean(values(index,2)); %average of values between 1910 and 1920 inclusive. 

這是一個很好的example來自Mathworks人的索引。也可以嘗試在幫助中輸入logical indexing

+0

這正是我所忽略的。我忘了邏輯索引在MATLAB中以這種方式工作:)。我知道我有太多的步驟,所以我來到這裏哈哈。 –

相關問題