How to restart a function when an if condition is met - function

How do I "restart" my function when an if condition is or isn't met.
In this pseudocode, if the if condition is met, I would like to stop what the function was doing and restart again.
function example()
.
.
.
for i in 1:N
for j in 1:N
if Mat[i,j] > 1
Mat[i,j] += restart? # Here the process should restart,
end
end
end

Rather than adding additional branching and complicating a function, return values offer a great ability for control flow in I.M.H.O. much cleaner fashion.
Adding a little separate function is simple
function do_thing_once!(mat)
# Returns true if successful
for i in 1:N
for j in 1:N
if mat[i,j] > 1
mat[i,j] += 123
return false
end
end
end
return true
end
function do_all_things!(mat)
success = false
while !success
success = do_thing_once!(mat)
end
end

Related

MATLAB recursive function [Factorials]

The code works but I am confused. When n==1, I am assigning a=1, shouldn't that overwrite the value and return only 1?
format compact
fct(5)
function a = fct(n)
if n==1
a = 1;
else
a = n*fct(n-1);
end
end
This is how I picture it... Below is a recursion/factorial diagram that shows the cascading effect of the recursive calls. At the deepest recursive call fct(1) is evaluated which is equal to 1 given by the first if statement. Each recursive call is therefore defined by a deeper recursive call. I typically like to decompose the recursive function until reaching its terminating case. I guess a way to phrase it is "a function within function" not so much of a loop.
Where, fct(1) → 1
format compact
fct(5)
function a = fct(n)
if n == 1
a = 1;
else
a = n*fct(n-1);
fprintf("%d\n",a);
end
end
Cumulative/Recursive Results:
2
6
24
120
ans =
120
My Preferred Structuring:
format compact
fct(5)
function a = fct(n)
if n > 1
a = n*fct(n-1);
else
a = n;
end
end

Is it impossible to assign output argument after completion of recursive loop in the function of MATLAB?

When the below function is executed, I get the following error message "Output argument "max_idx" (and maybe others) not assigned during call to "find_node"."
I think the problem is in the fact that some output is produced after recursive loop. How can I solve this?
function max_idx = find_node(wt)
persistent all_idx_max;
node_degree=sum(wt,2);
maxval = max(node_degree);
all_nodes_with_max_val = ismember(node_degree,maxval);
idx_max = find(all_nodes_with_max_val);
if isempty(all_idx_max)
all_idx_max=1:8;
end
if size(idx_max,1)==3
max_idx=all_idx_max(idx_max(1))
elseif size(idx_max,1)>1
all_idx_max=idx_max;
find_node(wt(idx_max,idx_max)); <--problem happens in this path
else
max_idx=all_idx_max(idx_max)
end
I forgot to add output to the recursive part
function max_idx = find_node(wt)
persistent all_idx_max;
node_degree=sum(wt,2);
maxval = max(node_degree);
all_nodes_with_max_val = ismember(node_degree,maxval);
idx_max = find(all_nodes_with_max_val);
if isempty(all_idx_max)
all_idx_max=1:8;
end
if size(idx_max,1)==3
max_idx=all_idx_max(idx_max(1))
elseif size(idx_max,1)>1
all_idx_max=idx_max;
***max_idx =*** find_node(wt(idx_max,idx_max)); <--problem happens in this path
else
max_idx=all_idx_max(idx_max)
end

(Corona SDK) Call function once from an "enterFrame" function

I'm wondering how it would be possible to call a function once from an "enterFrame" function in Corona SDK.
Let's say i have:
local function funa()
i = i+1
funb()
end
Runtime:addEventListener("enterFrame", funa)
Besides wanting 'i' to be incremented each frame, I also want to run "funb", but only one time instead of one time for each frame, but I can't find out how to do that.
Any ideas?
Besides the simpler and more obvious solution of using a global variable to keep track of this, you can use a closure. Example:
local
function funa()
local run_already = false
local i = 0
return function()
i = i+1
if not run_already then
funb()
run_already = true
end
end
end
funa = funa()
funa()
funa()
local run_flag = false
local function funa()
i = i+1
if not run_flag then
funb()
run _flag = true
end
end
Runtime:addEventListener("enterFrame", funa)
Now i will incremented each frame , but function will be called once.

Tips for function inside while loop and i=i+1, Matlab

I have a problem with a function in matlab. This specific function is for filtering light signals. As you can see below I added the coding I’ve used in the function and in the while loop itself. The code is written for a NXT Lego robot.
Is there any tip how to get the count variable ( i = i + 1 ) to work in the function, so we can plot Light(i)? Because we’re getting a bunch of error messages when we try different codes to make it work.
function [light] = filter_func( i)
lightI(i) = GetLight(SENSOR_3);
if i==1
light(i)=lightI(i)
elseif i==2
light(i) = 0.55*lightI(i) + 0.45*lightI(i-1)
else
light(i) = 0.4*lightI(i) + 0.3*lightI(i-1) + 0.3*lightI(i-2);
end
end
i=1
while true
lightI(i) = GetLight(SENSOR_3); % Get’s a lightvalue between 0 and 1024.
if i>2
light =filter_func(i)
light=round(light);
else
light(i) = GetLight(SENSOR_3);;
end
i=1+i
plot(light(end-90:end), 'r-');
title('Lightvalue')
axis([0 100 0 1023]) ;
end
You probably mainly get errors because you are not allowed to mix script and functions like this in MATLAB (like you are in Python).
Your filter function is only used when i>2 so why are you doing the first 2 tests? It seems like you want lightI as a global variable, but that is not what you have done. The lightI inside the function is not the same as the one in the while loop.
Since your while loop runs forever, maybe you don't need to worry about updating the plot the first two times. In that case you can do this:
filter = [0.4 0.3 0.3]';
latest_filtered_light = nan(90,1);
lightI = [];
p = plot(latest_filtered_light, 'r-');
title('Lightvalue')
axis([0 100 0 1023]) ;
while True
lightI(end+1,1) = rand*1024; % Get’s a lightvalue between 0 and 1024.
if i>=3
new_val = lightI(end-2:end,1)'*filter;
latest_filtered_light = [latest_filtered_light(2:end);...
new_val];
set(p, 'ydata', latest_filtered_light)
drawnow
end
end
I think it is an important point to not call plot every time - at least if you are the least concerned about performance.

Lua - How do I use a function from another script?

I've been looking around and I have not been able to find anything that has worked for me. I'm starting to learn more Lua and to start off I'm making a simple calculator. I was able to get each individual operation onto separate programs, but when I try to combine them I just can't get it to work. My script as it is now is
require "io"
require "operations.lua"
do
print ("Please enter the first number in your problem.")
x = io.read()
print ("Please enter the second number in your problem.")
y = io.read()
print ("Please choose the operation you wish to perform.")
print ("Use 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.")
op = io.read()
op = 1 then
function addition
op = 2 then
function subtraction
op = 3 then
function multiplication
op = 4 then
function division
print (answer)
io.read()
end
and my operations.lua script is
function addition
return answer = x+y
end
function subtraction
return answer = x-y
end
function multiplication
return answer = x*y
end
function division
return answer = x/y
end
I've tried using
if op = 1 then
answer = x+y
print(answer)
if op = 2 then
answer = x-y
print(answer)
and I did that completing each operation. But it doesn't work. I can't even get the error code that it's returning because it closes so fast. What should I do?
In your example, make these changes: You require operations.lua without the extension. Include parameters in your operations function definitions. Return the operation expression directly versus returning a statement like answer = x+y.
All together:
Code for operations.lua
function addition(x,y)
return x + y
end
--more functions go here...
function division(x,y)
return x / y
end
Code for your hosting Lua script:
require "operations"
result = addition(5,7)
print(result)
result = division(9,3)
print(result)
Once you get that working, try re-adding your io logic.
Keep in mind that as it's coded, your functions will be defined globally. To avoid polluting the global table, consider defining operations.lua as a module. Take a look at the lua-users.org Modules Tutorial.
The right if-then-else syntax:
if op==1 then
answer = a+b
elseif op==2 then
answer = a*b
end
print(answer)
After: please check the correct function-declaration syntax.
After: return answer=x+y is incorrect. If you want set answer's value, set without return. If you want return the sum, please use return x+y.
And I think you should check Programming in Lua.
First of all, learn to use the command line so you can see the errors (on Windows that would be cmd.exe).
Second, change the second line to require("operations"). The way you did it the interpreter expects a directory operations with an underlying script lua.lua.