How to iterate through a column vector elements one by one?
Afficher commentaires plus anciens
Hello Guys! I am new to matlab and working on a project. I want to iterarte through a column vector and retrive element of column one by one into another variable. That is, I want to retrive first element from a matrix of 1382x1 and then compute it and then the next element and so on. Kindly Help me out. I knw it would be using for loop but I cant find a solution.
4 commentaires
Prahlad Roy
le 7 Déc 2022
Voss
le 7 Déc 2022
Acc = sqrt(accel_x.^2+accel_y.^2+accel_z.^2)
or
accel = [accel_x accel_y accel_z];
Acc = sqrt(sum(accel.^2,2))
or
Acc = sqrt(sum([accel_x accel_y accel_z].^2,2))
So how do you want to get a single value from those 1382 Acc values?
Prahlad Roy
le 7 Déc 2022
Réponses (1)
Voss
le 5 Déc 2022
v = rand(1382,1); % 1382x1 column vector
N = numel(v);
final_result = zeros(N,1); % "another variable", the same size as v
for ii = 1:N
% retrieve ii-th element of v:
current_value = v(ii);
% do something with current_value to get a result:
current_result = current_value^2;
% store the result in the final_result vector:
final_result(ii) = current_result;
end
Or, without the use of the temporary variables current_value and current_result:
for ii = 1:N
% compute the result for the ii-th element of v, and
% store it in the final_result vector:
final_result(ii) = v(ii)^2;
end
However, depending on what your computation entails, you may be able to avoid the loop entirely. For example, the above can be written as:
final_result = v.^2;
Catégories
En savoir plus sur MATLAB dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!