REPEATING COMMAND BY FUNCTION
조회 수: 8 (최근 30일)
이전 댓글 표시
A small code has been created to check the a sensor's input variable value as per its scaling values. The code runs like this:
clear all;
clc;
sval=0;
p1='Please enter Minimum Range of Sensor Input : ';
smin=input(p1);
p2='Please enter Maximum Range of Sensor Input : ';
smax=input(p2);
p3='Please enter Minimum Range of Sensor Output : ';
inmin=input(p3);
p4='Please enter Maximum Range of Sensor Output : ';
inmax=input(p4);
rate=(smax-smin)/(inmax-inmin);
offset=smin-(inmin*rate);
show=['Your Scaling Rate will be : ',num2str(rate)];
disp(show)
show1=['Your Offset will be : ',num2str(offset)];
disp(show1)
p5='Do you want to calculate now [Y/N] : ';
str=input(p5,'s');
if str=='y' || str=='Y'
p6='Please enter output value of sensor : ';
inpt=input(p6);
if inpt<inmin || inpt>inmax
sprintf('Input value out of range')
else
sval=(inpt*rate)+offset;
show2=['Value input at sensor is : ',num2str(sval)];
disp(show2)
end
end
Now, after displaying the present values, we need to go back to the part where we ask the user whether they want to calculate now. In C++, we generally used the "GOTO" command for this. But we guess it is not available in Matlab. Also, when we tried to create a function, an error is shown as:
function recap
p5='Do you want to calculate now [Y/N] : ';
str=input(p5,'s');
"FUNCTION keyword use is invalid here. This might cause later messages about END. "
Please suggest some solution!!
댓글 수: 0
채택된 답변
Jan
2019년 4월 25일
편집: Jan
2019년 4월 25일
You should not use GOTO in any code, because it is massively unclear. Use a loop instead:
while true
p1='Please enter Minimum Range of Sensor Input : ';
smin=input(p1);
if isempty(smin)
break; % Break out of the WHILE loop
end
...
end
In modern Matlab versions a function can be created in a script also. In older versions (as far as I remember <= R2016a), functions can be defined in other function files only. Then some patterns must be considered:
function Outputs = main(Inputs)
...
end % <= If one function has a closing END, all functions need it
function Out = SubFunction(Ins)
end
Closing end statements are needed also, if nested functions are used.
댓글 수: 3
Jan
2019년 4월 25일
p5 = 'Do you want to calculate now [Y/N] : ';
str = input(p5, 's');
while strcmpi(str, 'y')
p6 = 'Please enter output value of sensor : ';
inpt = input(p6);
if inpt<inmin || inpt>inmax
sprintf('Input value out of range')
else
sval = (inpt*rate) + offset;
show2 = ['Value input at sensor is : ',num2str(sval)];
disp(show2)
% Ask for the next calculation again:
str = input(p5, 's');
end
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!