indexing multiple values in two arrays with different size
이전 댓글 표시
I have a simple problem that unfortunately I am failiing so solve (and to find solutions in internet).
Assuming I have 2 matrixes
a = [1 1 1 1 2 2 2 2 2 5 5 5; 0 0 0 0 0 0 0 0 0 0 0 0]';
b = [1 2 5; 11 12 15]';
I would like (without a for loop, that is my current, very slow implementation) to assign in a the corresponding values in the second column of b, when a(x, 1) == b(x,1). Basically the final result should be
a = [1 1 1 1 2 2 2 2 2 5 5 5; 11 11 11 11 12 12 12 12 12 15 15 15]
Thanks a lot for any help
채택된 답변
추가 답변 (1개)
Pietro
2019년 2월 14일
댓글 수: 4
madhan ravi
2019년 2월 14일
Typing short lines of code doesn't make the code efficient:
tic
for k=1:1e5
a(:,2) = interp1(b(:,1), b(:,2), a(:,1));
end
toc
tic
for k=1:1e5
A=sum(a(:,1)==b(:,1).');
a(:,2)=repelem(b(:,2),A).';
end
toc
Gives:
Elapsed time is 10.439265 seconds. % interp1() method
Elapsed time is 1.281436 seconds. % other method
Pietro
2019년 2월 14일
Pietro
2019년 2월 15일
madhan ravi
2019년 2월 15일
So instead of creating variable A in workspace why not directly implement it ?
a(:,2)=repelem(b(:,2),sum(a(:,1)==b(:,1).')).';
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!