How do I use a loop function for checking each numbers in a vector?
Show older comments
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
dpb
on 19 Sep 2019
Since this is obviously a homework problem, we won't write the whole solution for you. Will coach a little or if you ask a speific Q? on syntax or the like or after you show what you have done and where got stuck, provide hints.
First hint: It isn't the for function itself that does the condition checking, look at the doc for if for that. Of course, the assignment does say you must use the looping technique so reading and looking at the examples for it is bound to be useful as well. One would presume there's been examples of both illustrated in class as well.
Hint second: There are several ways to determine the unknown array size; the last word in first clause here should be a big clue as to one... :)
Hami the Penguin
on 21 Sep 2019
David Hill
on 21 Sep 2019
Look at what this does:
A>50
A<=50
A.*(A>50)/2
(10+A).*(A<=50)
A.*(A>50)/2 + (10+A).*(A<=50)
Bandar
on 21 Sep 2019
what about using numel()? It is not clear what do you mean by unknown.
dpb
on 21 Sep 2019
"I don't know how to use the while loop function to check each value in the vector."
As before, while isn't what does any checking and unless the HW assignment requires its use, for is by far the simpler route here.
Reread my previous hint carefully, the clue to how to find what you need is in the wording... :)
Hami the Penguin
on 21 Sep 2019
Edited: dpb
on 21 Sep 2019
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.
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!