Jose Ramon
Jose Ramon

Reputation: 5444

Process a matrix in matlab without for loop

I have got a matrix Nx3 dimension in matlab. I want to calculate the norm of every n-th row of the matrix. However I want to perform the norm calculation without using for loop. Is there a way to do so? My for loop code:

for i=1:length(accelerometer)
   magnitude(i,:) = sqrt(accelerometer(i,1)^2 + accelerometer(i,2)^2+   accelerometer(i,3)^2);
end

Upvotes: 1

Views: 141

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112689

Let A be your matrix.

  • If "every n-th row" means rows 1, n+1, 2*n+1,...:

    result = sqrt(sum(abs(A(1:n:end,:)).^2, 2));
    
  • If it simply means "every row":

    result = sqrt(sum(abs(A).^2, 2));
    

In either case, if A is real you can remove abs.

Upvotes: 3

Bentoy13
Bentoy13

Reputation: 4966

The dot function may also help you. Calling A your input matrix, and n the row step:

result = sqrt(dot(A(1:n:end,:), A(1:n:end,:), 2));

But note that if A is complex, the result will be complex, it's equivalent to this answer only for a real matrix.

Upvotes: 1

Digol
Digol

Reputation: 390

You can do it this way:

x=[2 3 4;2 3 2;4 5 6];

magnitude=sum(x')';

ans =

     9
     7
    15

If x is complex at any point :

x=[2 3 4;2 3 2;4 5 6+1i];

magnitude_Complex=abs(sum(x')');


ans =

    9.0000
    7.0000
   15.0333

Upvotes: 1

Related Questions