Vectorize Matrix Formation & Multiplication

조회 수: 1 (최근 30일)
Fawad Farooq Ashraf
Fawad Farooq Ashraf 2022년 11월 17일
댓글: Fawad Farooq Ashraf 2022년 11월 17일
How can I vectorize the following code
clear;clc
t = 1:10;
v = rand(10,3);
a = rand(10,1);
m = 6:15;
n = 6:15;
M = 1:20;
N = 1:20;
P = ones(20,20);
V = zeros(size(v))';
D = zeros(size(m))';
for i = 1:length(t)
B = [1,0,0;0,cos(a(i)),sin(a(i));0,-sin(a(i)),cos(a(i))];
V(:,i) = B*v(i,:).';
D(i,1) = interp2(M,N,P,m(i),n(i));
end
V = V.'; % (size has to be same as v)
how can I rewrite this code without using loops?

채택된 답변

Matt J
Matt J 2022년 11월 17일
편집: Matt J 2022년 11월 17일
N=length(t);
a=reshape(a,1,1,N);
B=zeros(3,3,N) ;
B(1,1,:)=1;
B(2:3,2:3,:)=[cos(a), sin(a); -sin(a),cos(a)];
V = pagemtimes(B,reshape(v',2,1,N));
V=reshape(V,2,[]).';
D = interp2(M,N,P,m,n);
  댓글 수: 1
Fawad Farooq Ashraf
Fawad Farooq Ashraf 2022년 11월 17일
thank you. this works indeed
although, a minor correction may be
V = pagemtimes(B,reshape(v',3,1,N));
V=reshape(V,3,[]).';
as v has 3 columns instead of 2

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Descriptive Statistics and Visualization에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by