How to get values from index in a matrix?

2 views (last 30 days)
Paul Hinze
Paul Hinze on 23 Jan 2021
Commented: dpb on 23 Jan 2021
x = [Structure.GK_10.GA_0; Structure.GK_10.GA_10; Structure.GK_10.GA_20; Structure.GK_10.GA_30;...
Structure.GK_10.GA_40; Structure.GK_10.GA_50];
[row,col] = size(x);
for i = 1:row
not_zero = find(x(i,:) ~= 0);
%DOES NOT WORK val_not_zero = x(i(not_zero,:));
mean_first_15 = mean(val_not_zero(1:15));
end
Hello,
i just want to tranfer the indices into real values again, but how can i do it in a matrix. In this loop i i grab the indices that are not zero in the first row. Then i try to get the values in the next line, but it doesnt work, can someone help me?
  3 Comments
dpb
dpb on 23 Jan 2021
mean_first_15 = mean(val_not_zero(1:15));
Besides Walters correction to index into the x array by row, column, the above will fail if there aren't at least 15 nonzero elements in a given row; to do that you would need to handle that condition.
mean_first_15 = mean(x(i,not_zero(1:min(numel(not_zero),15)));
(I think I counted parentheses correctly... :) )
If that isn't of concern as isn't in Walter's code, then you can eliminate the loop entirely by putting in a NaN indicator for zero--
x(x==0)=nan;
meanx=mean(x,2,'omitnan');
That again, however, doesn't limit the number considered in a row but includes the whole array.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!