Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 有条件地选择矩阵的行_Arrays_Matlab - Fatal编程技术网

Arrays 有条件地选择矩阵的行

Arrays 有条件地选择矩阵的行,arrays,matlab,Arrays,Matlab,我正在寻找一种更有效的方法,在MATLAB中完成一项简单的任务。我的代码可以工作,但对于我想要完成的任务来说似乎过于冗长。我有一个带有相应值的年份矩阵,其中年份可以重复。例如: ... 1910 1.04 1910 2.53 1910 0.94 1911 2.13 1911 5.32 ... 我想选择一个年份范围,然后取第二列中所有年份在该范围内的值的平均值。我目前的做法是 years = rawdata(:,yearcolumn); %extracts y

我正在寻找一种更有效的方法,在MATLAB中完成一项简单的任务。我的代码可以工作,但对于我想要完成的任务来说似乎过于冗长。我有一个带有相应值的年份矩阵,其中年份可以重复。例如:

...

1910 1.04

1910 2.53

1910 0.94

1911 2.13

1911 5.32

...
我想选择一个年份范围,然后取第二列中所有年份在该范围内的值的平均值。我目前的做法是

years = rawdata(:,yearcolumn);             %extracts year vector from data
rows_to_keep = years>=firstyear_i&years<maxyear;  %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
years=rawdata(:,yearcolumn);%从数据中提取年份向量

行到保持=年>=第一年我&年有太多的步骤。只需使用你想要的索引,然后取平均值。像这样:

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.503333

要只保存内容(而不是以后删除所有内容),请执行以下操作

如果您想保留信息供以后使用,只需保存索引并在需要时调用即可

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.

index=values(:,1)>=1910&values(:,1)这正是我忽略的。我忘了逻辑索引在MATLAB中是这样工作的:)。我知道我有太多的步骤,所以我来这里,哈哈。
index = values(:,1) >= 1910 & values(:,1) <= 1920;
mean(values(index,2)); %average of values between 1910 and 1920 inclusive.