Conditional Statements & Loops
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Steven Lord
el 28 de Abr. de 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.
Respuestas (1)
Steven Lord
el 28 de Abr. de 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
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!