Conditional Statements & Loops
조회 수: 11 (최근 30일)
이전 댓글 표시
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
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.
답변 (1개)
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!