Effacer les filtres
Effacer les filtres

Vectorize Matrix Formation & Multiplication

1 vue (au cours des 30 derniers jours)
Fawad Farooq Ashraf
Fawad Farooq Ashraf le 17 Nov 2022
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?

Réponse acceptée

Matt J
Matt J le 17 Nov 2022
Modifié(e) : Matt J le 17 Nov 2022
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 commentaire
Fawad Farooq Ashraf
Fawad Farooq Ashraf le 17 Nov 2022
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

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by