How to iterate through a column vector elements one by one?
이전 댓글 표시
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
Prahlad Roy
2022년 12월 7일
Voss
2022년 12월 7일
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
2022년 12월 7일
답변 (1개)
Voss
2022년 12월 5일
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;
카테고리
도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!