Effacer les filtres
Effacer les filtres

How can I populate the rows of a difference matrix without using a for loop?

2 vues (au cours des 30 derniers jours)
I am creating Matlab code to construct the following matrix:
In my data, x and y are 101-dimensional real vectors and N is a vector of six real numbers. My Matlab implementation is
% Real inputs of length 101 for x,y and length 6 for X,Y
x = rand(1,101);
y = rand(1,101);
X = rand(6,1);
Y = rand(6,1);
n = length(x);
N = length(X);
G = zeros((N-1),2,n);
% Distance calculation
d = @(k) sqrt((X(k) - x).^2 + (Y(k) - y).^2); % L2 Norm / Euclidean distance
xdiff = @(k) (((X(1) - x) ./ d(1)) - ((X(k+1) - x) ./ d(k+1)));
ydiff = @(k) (((Y(1) - y) ./ d(1)) - ((Y(k+1) - y) ./ d(k+1)));
GBlock = @(k) [xdiff(k) ydiff(k)];
% This seems inefficient - is there a better alternative?
Z = all(G>=0,2);
for k = 1:size(G,1)
if Z(k)
G(k,:) = GBlock(k);
end
end
Creating Gblock followed by a for loop seems inefficient. Is there a way to vectorize this code and avoid writing a for loop?
  3 commentaires
Matthew Kehoe
Matthew Kehoe le 17 Oct 2023
Modifié(e) : Matthew Kehoe le 18 Oct 2023
Yes, I incorrect indexed two locations of x and y. I have updated my original question.
Matt J
Matt J le 17 Oct 2023
Very well, but what about my answer below?

Connectez-vous pour commenter.

Réponse acceptée

Matt J
Matt J le 16 Oct 2023
Modifié(e) : Matt J le 16 Oct 2023
X=X(:);
Y=Y(:);
x=reshape(x,1,1,[]);
y=reshape(y,1,1,[]);
d=hypot( X - x , Y - y );
Diff=@(U,u) ((U(1)-u)./d(1,1,:)) - ((U(2:end) - u) ./ d(2:end,1,:));
G=[Diff(X,x), Diff(Y,y)];

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by