Creating vectors by rand() and looping it

4 views (last 30 days)
The question: Create a vector A with 10 integer numbers by rand(), and ceil() or floor() or round. Each number is between 5 and 20. Then iterate through the vector and return a new vector B, containing the true wherever an element of A is greater than 12, and false otherwise.
Use loop(for loop or while loop). Do not use vector operations. Please display both A and B.
I started off creating
a=5
b=20
vector=(b-a)*rand(10,1)+a
ceil(vector)
for the first part with 10 integer between 5-20. I'm little lost in what to do with the next steps, esp the loop.

Accepted Answer

James Tursa
James Tursa on 4 Oct 2019
Good start, but do this to save the ceil function result back into vector:
vector = ceil(vector);
For the next part you need a loop. Since you know you will be iterating on each element of A, a for loop with indexing from 1 to numel(A) would be appropriate. To write the code, first just plop the words of the assignment right into the editor like this:
a = 5;
b = 20;
vector = (b-a)*rand(10,1) + a;
vector = ceil(vector);
for iterate through the vector % turn into code
new vector B, containing the true wherever an element of A is greater than 12, and false otherwise % turn into code
end
Please display both A and B % turn into code
Once you have that in the editor, try to turn each line that I have indicated into code ... each line may turn into several lines of code. Give it a shot and then come back to us with you attempts and any problems you are having with these next steps.
  2 Comments
Stephen23
Stephen23 on 4 Oct 2019
Davifus's "Answer" moved here:
a = 5;
b = 20;
vector = (b-a)*rand(10,1) + a;
vector = ceil(vector);
for i=vector
if vector>12
disp('true')
else
disp('false')
end
end
Im not sure if this is even remotley correct. Just having a hard time with loop&iterate.
James Tursa
James Tursa on 4 Oct 2019
So, I gave you a clue when I wrote " for loop with indexing from 1 to numel(A)". So this:
for i=1:numel(A)
Then inside this loop, you need to assign a value to B(i) based on the value of A(i).
After the for loop is done, then display both A and B

Sign in to comment.

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!