Conditional Statements & Loops

조회 수: 11 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by