# Creating for loop for a piecewise function

54 vues (au cours des 30 derniers jours)
Petch Anuwutthinawin le 12 Juin 2021
I have made a piecewise function using if statements that inputs Vs as a vector and outputs VL as a number. I need to loop this piecewise function for each element of the input vector, each loop I need it to display the VL output into a row vector.
if Vs<=0.6; %if this is true
VL=0;% it prints a 0
else
VL=Vs-0.6; % prints a Vs-0.6 value.
end
%I need to make a for loop that will loop this for the entire vector input of Vs and display all the values in a
% row vector.
%I have tried to make a loop as follows:
for V=0:Vs;
if V<=0.6; %if this is true
VL(V)=0;% it prints a 0
else
VL(V)=V-0.6; % prints a Vs-0.6 value.
end
end
%All this outputs is zero, and it does not loop and does not output a
%vector.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Star Strider le 12 Juin 2021
One problem is that MATLAB subscripts are integers greater than 0, so setting ‘V’ to 0 and using it as a subscript will fail.
Try this —
Vs = 5; % Create Value
Vv=0:Vs; % Define As A Vector
for k = 1:numel(Vv)
if Vv(k)<=0.6; %if this is true
VL(k)=0;% it prints a 0
else
VL(k)=Vv(k)-0.6; % prints a Vs-0.6 value.
end
end
VL
VL = 1×6
0 0.4000 1.4000 2.4000 3.4000 4.4000
.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by