How do I use a loop function for checking each numbers in a vector?

7 次查看(过去 30 天)
I have a question which I am struggling to solve:
Given a vector, A, of UNKNOWN length. Traverse each element of the vector and determine if the value is greater than or less than 50. If the element is less than 50, then add 10 to the value and place it back in the same element. If the element is greater than or equal to 50, then divide the value by 2 and place it back in the same element. A=[44,64,82,32,16,94,22,88,24,56];
You must use a for loop with an if/else embedded in the body of the loop. Caution: You must treat the vector as if the length is UNKNOWN.
For this question, I don't know how I use the for function for checking if each value exceeds 50 or not in the vector.
Can someone help me solve this problem?
Thank you.
  7 个评论
Hami the Penguin
Hami the Penguin 2019-9-21
编辑:dpb 2019-9-21
This is what I tried:
clear all;
clc;
for i=1:1:length(A)
A(1,i)
if i < 50
i = i + 10;
else
i = i / 2;
end
A(1,i);
end
A
However, it still didn't work. I am having problem setting 'i' as the value of each elements in the vector.
dpb
dpb 2019-9-22
You used i for the index of the array but then just tested for it, not the content of the array at that location (which you did display before/after) but you never did anything to those elements other than display them.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by