Multidimensional array indexing question
Show older comments
I have a matrix x that is of size [61 2 45].
linearIndex = find(x(:,1,:) < x(:,2,:));
xAverage = (x(:,1,:) + x(:,2,:))/2;
Now I want to assign the average to anywhere x(:,1,:) < x(:,2,:). I come up with the following but it seems a bit verbose and un-elegant. Thoughts on how to do this better?
[subScriptIndex1, subScriptIndex2, subScriptIndex3] = ind2sub(size(linearIndex), linearIndex);
x(subScriptIndex1, 1, subScriptIndex3) = xAverage(subScriptIndex1, 1, subScriptIndex3);
x(subScriptIndex1, 2, subScriptIndex3) = xAverage(subScriptIndex1, 1, subScriptIndex3);
1 Comment
Jason Nicholson
on 8 Aug 2016
Accepted Answer
More Answers (1)
Fangjun Jiang
on 8 Aug 2016
x=rand(6,2,4);
MeanX=mean(x,2);
idx=x(:,1,:) < x(:,2,:);
x(idx)=MeanX(idx);
3 Comments
Jason Nicholson
on 8 Aug 2016
Edited: Jason Nicholson
on 8 Aug 2016
Fangjun Jiang
on 8 Aug 2016
How about this? I think it works but what if the second dimension is larger than 2? There must be a a better way.
x=rand(6,2,4);
MeanX=mean(x,2);
MeanX(:,2,:)=MeanX(:,1,:);
idx=x(:,1,:) < x(:,2,:);
idx(:,2,:)=idx(:,1,:);
x(idx)=MeanX(idx);
Jason Nicholson
on 9 Aug 2016
Edited: Jason Nicholson
on 9 Aug 2016
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!