MATLAB: How to group variable of interests by logical indexing

group variablelogical indexing

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

Best Answer

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