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

7 views (last 30 days)
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 Comments
Hami the Penguin
Hami the Penguin on 21 Sep 2019
Edited: dpb on 21 Sep 2019
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 on 22 Sep 2019
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.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!