How to vectorize?
3 次查看(过去 30 天)
显示 更早的评论
Hi, is it possible to avoid the loop? Thanks.
x=(1:3:r);
[r,c]=size(Tr);
E1=zeros(r,c);
for i=1:c
E1(x,i)=E(Tr(r,i),i);
end
>> size(Tr)
ans =
21 6
5 个评论
Image Analyst
2023-7-29
Not seeing it. Again, what is Tr and E (not E1, but E)?
Does your for loop even work? What is the desired output?
If you have any more questions, then attach your data and missing code to read it in after you read this:
采纳的回答
Bruno Luong
2023-7-30
编辑:Bruno Luong
2023-7-30
Just to pull out the right answer (my previous answer applied on a WRONG calculation specified by OP)
% vectorized method
c = size(Tr,2);
m = size(E,1);
x = 1:step:m;
E1 = zeros(size(Tr));
E1(x,:) = E(Tr(x,:) + (0:c-1)*m);
2 个评论
Bruno Luong
2023-7-30
编辑:Bruno Luong
2023-7-30
OP is Original Poster, it's you who wrote : "excuse me.. z=r...i change it in code" ... remember?
My answer (not the comments below it) is wrong because the question is wrong.
更多回答(1 个)
Bruno Luong
2023-7-29
编辑:Bruno Luong
2023-7-29
If you want obscure code by avoiding for-loop
E = rand(10,5)
Tr = randi(size(E,1),9,size(E,2))
[r,c]=size(Tr);
x=(1:3:r);
[r,c]=size(Tr);
x=(1:3:r);
% Your method
E1=zeros(r,c);
for i=1:c
E1(x,i)=E(Tr(r,i),i);
end
E1
% vectorized method
E1=zeros(r,c);
i=1:c;
E1(x(:) + (i-1)*r) = repmat(E(Tr(r,i) + (i-1)*size(E,1)),length(x),1);
E1
13 个评论
Bruno Luong
2023-8-2
编辑:Bruno Luong
2023-8-2
Code to handle the case Tr == 0
c = size(Tr,2);
m = size(E,1);
x = 1:step:m;
E1 = zeros(size(Tr));
Trx = Tr(x,:);
iE = Trx + m*(0:c-1);
tmp = E(max(iE,1));
tmp(Trx == 0) = 0;
E1(x,:) = tmp;
it does not handle still the case Tr > m or Tr < 0.
If you havve data that are not valid for proper indexing it will be a mess to deal with.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!