Taking the norm of every 1x3 vector inside a 60x3 data

4 views (last 30 days)
r = dlmread('position.txt');
v = dlmread('velocity.txt');
t = dlmread('time.txt');
r is 60x3 matrix, and I was wondering how I can write a loop statement that takes the norm of every row and storing it. Thank you!

Answers (3)

KSSV
KSSV on 24 Apr 2020
If A is your 60*3 matrix..
iwant = sqrt(A(:,1).^2+A(:,2).^2+A(:,3).^2) ;
  3 Comments
Felix Marrar
Felix Marrar on 24 Apr 2020
I got it.
for i = 1:1:60 %% for every value from 1 to 60
x = norm(r(i,:)); %% this takes the norm of every row in r, 60 times
y = norm(v(i,:));
z = norm(h(i,:));
rNorms(i,:) = x %% this stores it in an array in every row and column
vNorms(i,:) = y
hNorms(i,:) = z
end
Bjorn Gustavsson
Bjorn Gustavsson on 24 Apr 2020
Yeah, that gets the job done.
One thing you should consider (it is not that important for array-sizes this small, but you'll get to larger problem in a very short time...) is to pre-allocate the arrays. As it works now your rNorms, vNorms and hNorms arrays are saved in 1x1 arrays first time around the loop, second step these arrays will be automatically reallocated to 2x1 arrays, then 3x1 etc. When the arrays becomes large this array-reallocation step becomes time-consuming. To avoid that you can initialize the variable (in your case you know the size of the outputs):
nRows = size(r,1); % Try to avoid hard-coded numbers
rNorm = zeros(nRows,1); % etc
In some situations where one might have to think to figure out the sizes but it is possible to run the loops in any order one might get the same effect by looping down:
for iR = nRows:-1:1 %% for every value from 60 to 1
rNorms(iR) = norm(r(iR,:));
end
Then when you've mastered looping you should next turn to the vectorized operations where optimized library-functions handle the matrix-calculations.

Sign in to comment.


Mehmed Saad
Mehmed Saad on 24 Apr 2020
There is a shorter way of doing that i.e. without for loop
  1. convert array to cell
  2. apply cellfun
suppose
r = rand(60,3);
convert array to cell (mat2cell)
cr = mat2cell(r,ones(1,length(r)));
apply cellfun to cell
rNorms = cellfun(@norm,cr);
You can do that in 1 command as
rNorms = cellfun(@norm,mat2cell(r,ones(1,length(r))));
  2 Comments
Bjorn Gustavsson
Bjorn Gustavsson on 24 Apr 2020
I have you beat in golfing, see comment above, repeated here:
rNorms = sqrt(sum(A.^2,2));

Sign in to comment.


Steven Lord
Steven Lord on 24 Apr 2020
Use the vecnorm function.
A = gallery('moler', 6)
normOfEachColumn = vecnorm(A)
twoNormEachRow = vecnorm(A, 2, 2)
checkNormOfThirdRow = norm(A(3, :), 2) % Should match twoNormEachRow(3)

Tags

Community Treasure Hunt

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

Start Hunting!