How to find vector with if loops and for loops

1 回表示 (過去 30 日間)
Ömer Durkut
Ömer Durkut 2022 年 6 月 15 日
編集済み: Torsten 2022 年 6 月 24 日
Given a vector u with the dimension 20x1, which consists of random variables from a uniform distribution (distributed on [0,1]) exists. Instructions: • Create a code in MATLAB, – which creates the vector u, – which contains both ’for loops’ and ’if loops’, – and for all values in the vector u indicates in which quarter the number lies.This is one of my mathlab final exam question, could you please help me,i just know that i should use "rand" function
  4 件のコメント
Torsten
Torsten 2022 年 6 月 15 日
Ok, then - under the link given - you get the hints the forum is willing to give to solve this assignment.
Ömer Durkut
Ömer Durkut 2022 年 6 月 15 日
Thanks a lot

サインインしてコメントする。

採用された回答

Image Analyst
Image Analyst 2022 年 6 月 16 日
Are you allowed to turn in other people's solutions as your own for your final exam question?
The first 5 values of the 20-element u lie in the first quarter, the next 5 in the second quarter, the third 5 in the third quarter, and the final 5 elements in indexes 16-20 obviously lie in the last quarter. But I think they want you to use a for loop
u = rand( % You said you got this
for k = 1 : length(u)
if u(k)...........
More code
end
end
You can either store the quarter that the number lives in, in a vector called quarter, or maybe you just want to print out the quarter it's in using fprintf(). Or maybe you want to do both.
  15 件のコメント
Image Analyst
Image Analyst 2022 年 6 月 24 日
@Jan, true. I just basically took the OP's code but an experienced programmer would do it more like this:
n = 20;
r = rand(n,1);
for k = 1 : numel(r)
if r(k) < 0.25
quarter(k) = 1;
elseif r(k) < 0.50
quarter(k) = 2;
elseif r(k) < 0.75
quarter(k) = 3;
else % r(k) >= 0.75
quarter(k) = 4;
end
end
quarter
Torsten
Torsten 2022 年 6 月 24 日
編集済み: Torsten 2022 年 6 月 24 日
I like if the order of the conditions in if-statements can be changed.
This is not the case in this simplified version because
if r(k) < 0.75
quarter(k) = 3;
elseif r(k) < 0.25
quarter(k) = 1;
elseif r(k) < 0.5
quarter(k) = 2;
else
quarter(k) = 4;
end
would create chaos.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by