Taking the norm of every 1x3 vector inside a 60x3 data
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
2 commentaires
Réponses (3)
KSSV
le 24 Avr 2020
If A is your 60*3 matrix..
iwant = sqrt(A(:,1).^2+A(:,2).^2+A(:,3).^2) ;
3 commentaires
Bjorn Gustavsson
le 24 Avr 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.
Mehmed Saad
le 24 Avr 2020
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 commentaires
Bjorn Gustavsson
le 24 Avr 2020
I have you beat in golfing, see comment above, repeated here:
rNorms = sqrt(sum(A.^2,2));
Steven Lord
le 24 Avr 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)
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!