Conditional Statements & Loops

12 ビュー (過去 30 日間)
Wenlong Yu
Wenlong Yu 2020 年 4 月 28 日
回答済み: Steven Lord 2020 年 4 月 28 日
Write a matlab FUNCTION named prob2 that inputs a vector of values named x and returns a corresponding vector of values named y according to the following rules.
y = -x-pi when x <= -p
y = sin(x) when -pi<x<=pi
y = -x+pi when pi<x
Hint: you will need to use a loop
  2 件のコメント
Steven Lord
Steven Lord 2020 年 4 月 28 日
This sounds like a homework assignment. If it is, show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the MATLAB Onramp tutorial (https://www.mathworks.com/support/learn-with-matlab-tutorials.html) to quickly learn the essentials of MATLAB.
If you aren't sure where to start because you're not familiar with the mathematics you'll need to solve the problem, I recommend asking your professor and/or teaching assistant for help.
Wenlong Yu
Wenlong Yu 2020 年 4 月 28 日
編集済み: Steven Lord 2020 年 4 月 28 日
function y = prob2(x)
y =[];
for i=1:1:length(x)
if x(i) <= -pi
y = -i-pi;
elseif x(i) > -pi && x(i) <= pi
y = sin(x(i));
else
y = -i + pi;
end
end
end
and it said Variable y must be of size [1 5]. It is currently of size [1 1]. Check where the variable is assigned a value.
[SL: removed last line from the code block]

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

回答 (1 件)

Steven Lord
Steven Lord 2020 年 4 月 28 日
Each time you process an element of x, you're overwriting the whole of y. You want to overwrite only the element in y corresponding to that element in x. So if you operate on x(i) you want to store the result in y(i).
I also recommend preallocating y to be the same size as x. In your case you're going to be assigning to an element of y no matter what code path you take through the body of your for loop, but if you hadn't (if you had a condition for x that didn't assign a value explicitly to y) you could end up with a y vector with fewer elements than x.
y = zeros(size(x)) % array the same size as x, all elements of y are 0

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by