Conditional Statements & Loops

10 views (last 30 days)
Wenlong Yu
Wenlong Yu on 28 Apr 2020
Answered: Steven Lord on 28 Apr 2020
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 Comments
Steven Lord
Steven Lord on 28 Apr 2020
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 on 28 Apr 2020
Edited: Steven Lord on 28 Apr 2020
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]

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 28 Apr 2020
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

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!