Filter löschen
Filter löschen

Creating vectors by rand() and looping it

10 Ansichten (letzte 30 Tage)
Davifus
Davifus am 4 Okt. 2019
Kommentiert: James Tursa am 4 Okt. 2019
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.

Akzeptierte Antwort

James Tursa
James Tursa am 4 Okt. 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 Kommentare
Stephen23
Stephen23 am 4 Okt. 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 am 4 Okt. 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by