How to avoid repetition?
显示 更早的评论
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 个评论
Amy Chen
2018-8-31
Adam
2018-8-31
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.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!