How to group variable of interests by logical indexing?
3 次查看(过去 30 天)
显示 更早的评论
I have this sort of data. I want to plot PAW with Pasture 9 Patch 1, Pasture 9 with Patch 3, along with Pasture 9 with Patch 5. I want to use logical indexing as, Pasture (Pasture==9), Patch(Patch==1) and then retrieve PAW data based on it. I tried this,
for ii =1:length(PAW)
Pasture_index = find(Pasture==9);
PAW40pasture(ii) = mean(PAW40(Pasture_index,1));
end
But this did not work. Any suggestions/help will be appreciated.
Pasture Patch PAW
9 1 59.90366347
9 1 58.71485861
9 1 57.35723603
9 1 57.36212973
9 3 57.04769458
9 3 127.7284367
9 3 143.7897127
9 3 143.5349223
9 3 142.5156813
9 5 142.3629269
9 5 148.7025447
9 5 149.7302998
9 5 147.5149873
9 5 88.55115557
9 5 80.52936618
采纳的回答
Guillaume
2016-3-2
First, you're not using logical indexing in your code because of the find. The exact same code without the call to find (i.e. Pasture_index = Pasture==9;) would be using logical indexing.
It's not clear to me why you thought the snippet you wrote would produce the result you want since you never filter for a given patch value.
If all you want is to produce the mean of PAW for identical combinations of pasture and patch then you don't need a loop and just need accumarray:
[ppval, ~, rows] = unique([Pasture, Patch], 'rows'); %assuming that Pasture and Patch are column vectors
PAW40pasture = accumarray(rows, PAW40(:, 1), [], @mean);
out = array2table([ppval, PAW40pasture], 'VariableNames', {'Pasture', 'Patch', 'mean'}) %this line just for pretty display
If you wanted to plot them (against what x axis?) then you could do it with a loop as follows:
figure; hold on;
ppvalues = unique([Pasture, Patch]);
for ppvalue = ppvalues'
inpasturepatch = Pasture == ppvalue(1) & Patch == ppvalue(2); %This is logical indexing. No find
plot(PAW40(inpasturepatch, 1), 'DisplayName', sprintf('Pasture %d, Patch %d', ppvalue(1), ppvalue(2)));
end
更多回答(1 个)
Image Analyst
2016-3-2
Do you have the stats toolbox? It looks like your data is in a table. You might be able to get the mean for all numbers very easily in one line of code with grpstats:
statarray = grpstats(tbl,groupvar)
6 个评论
Image Analyst
2016-3-2
You accepted an answer and said thanks, so I'm assuming you got everything working and this doesn't apply anymore.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Polygons 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!