Info

This question is closed. Reopen it to edit or answer.

I honestly have no clue where to start with this much help is needed and I really can't figure out how to put an "if" statement inside a switch statement?

1 view (last 30 days)
2. A vector, x, is given below.
a) set up a "for" loop to run over all elements of x - use the "length" command
b) inside the "for" loop, use an "if" construct to find any value of x that is less than or equal to 5 and to find any value of x that is greater than 5.
c) for the elements of x that are less than or equal to 5, use a "switch" construct to make that element equal to its square if the element equals to 5; otherwise, make the element of x equal to 1
d) for the x values that are greater than 5, make those elements of x equal to zero.
fprintf('\n\n#2\n')
clear all
x=[1 9 2 8 3 7 4 6 5];disp(x);
  2 Comments
James Tursa
James Tursa on 12 Oct 2016
Edited: James Tursa on 12 Oct 2016
What have you done so far? What specific problems are you having with your code? Do you know how to write a for-loop? A switch-statement? An if-test?
dpb
dpb on 13 Oct 2016
Edited: dpb on 13 Oct 2016
"... how to put an "if" statement inside a switch statement?"
Actually, the switch block is to go inside an if construct the way the assignment is written.
As for where to start, do the first step a). Then attack the next. It's pretty straightforward if you just follow the instructions step-by-step.

Answers (1)

Soma Ardhanareeswaran
Soma Ardhanareeswaran on 20 Oct 2016
Semantically, 'switch' statement is a collection of if-else-if statements. But if you still want an 'if' inside a switch case, here is a quick example:
switch n
case -1
if n/(-1)==1
disp('inside if')
end
case 0
disp('zero')
case 1
disp('positive one')
otherwise
disp('other value')
end

This question is closed.

Tags

Community Treasure Hunt

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

Start Hunting!