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

4 次查看(过去 30 天)
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!

回答(3 个)

KSSV
KSSV 2020-4-24
If A is your 60*3 matrix..
iwant = sqrt(A(:,1).^2+A(:,2).^2+A(:,3).^2) ;
  3 个评论
Felix Marrar
Felix Marrar 2020-4-24
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 2020-4-24
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.

请先登录,再进行评论。


Mehmed Saad
Mehmed Saad 2020-4-24
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))));

Steven Lord
Steven Lord 2020-4-24
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)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by