How to avoid repetition?
Show older comments
I have this code here and it does what I want it to do just fine. however theres a lot of repetition. I was wondering if there was a way to make it better, maybe even remove the for loop?
A = randi(10,5,5,5);
B = randi(4,5,5);
C = zeros(4,1,5);
layer1 = A(:,:,1); %separate 3rd dimension
layer2 = A(:,:,2);
layer3 = A(:,:,3);
layer4 = A(:,:,4);
layer5 = A(:,:,5);
for i = 1:4
value = B == i; %create a logical index for values from 1-4 in B
C(i,:,1) = mean(layer1(value));
C(i,:,2) = mean(layer2(value));
C(i,:,3) = mean(layer3(value));
C(i,:,4) = mean(layer4(value));
C(i,:,5) = mean(layer5(value));
end
2 Comments
Amy Chen
on 31 Aug 2018
Adam
on 31 Aug 2018
Even without vectorisation, from the perspective of purely how much code you write you should never be creating 5 variables as 5 layers of another array. The 5 layers you want are all already there in A, just index into them.
Then the indexing would be obvious to be able to create a nested for loop (from 1 to 5, indexing into A(:,:,1-5) rather than 5 named variables).
When you have the simpler nested for loop it is then often a lot easier to see how to vectorise the code. Or you could try to jump straight to the vectorisation. The intermediate step often just helps with understanding the process.
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!