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
2020-4-24
If A is your 60*3 matrix..
iwant = sqrt(A(:,1).^2+A(:,2).^2+A(:,3).^2) ;
3 个评论
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
2020-4-24
There is a shorter way of doing that i.e. without for loop
- convert array to cell
- 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 个评论
Bjorn Gustavsson
2020-4-24
I have you beat in golfing, see comment above, repeated here:
rNorms = sqrt(sum(A.^2,2));
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)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!