0

I have the following working function (a). This function is responsible to solve error within another function.

function [a] = algorithm1(z)
if (z==0)
    j=1;
    a=j;
    disp('Your computer is switch on from state offline')
elseif (z==1)
    j=1;
    a=j;
    disp('Your computer is working properly')
elseif (z==2)
    %j=2;  Value 2 for status of rebooting
    disp('Your computer is rebooting')
    j=1;
    a=j;
    disp('Your computer is working properly after rebooting')
else
    disp('unidentified error')
end

end 

My problem is how to make another function(b) that will take the function(a) above as its solution. I was hoping it would come out like this

T=100 status 1, your computer is working properly
T=101 status 1, your computer is working properly
T=102 status 2, your computer is working properly after rebooting
.
.
.
T=200 status 1, your computer is working properly

The T is a looping function and the status function(b) is generated randomly. How can I give function (a) to function (b) so that it will continously solve error using function (a).

0

1 Answer 1

1

If you want to pass a function to another function you need to use a function handle to an anonymous function.

The general syntax looks like this:

handle = @(input1, input2)function_to_call(input1, other_input, input2)

In your case, you could write function b like this

function b(afunction)
    for k = 1:100
        afunction(randi([1 2]));
    end
end

Then call b passing it a handle to a.

afunction = @(z)a(z);
% or just: afunction = @a

b(afunction)

Alternately, if both a and b are on your path, you can simply call a directly from b.

function b()
    for k = 1:100
        a(randi([1 2]));
    end
end
Sign up to request clarification or add additional context in comments.

2 Comments

I'm sure you know this, but I'll be pedantic because I see the terms mis-used all of the time: an anonymous function is not "also called a function handle." The link indicates the, perhaps subtle, difference. I like to think of the two in the same way as a pointer and a memory address.
@horchler I agree that it's a subtle but important distinction. I'll update it. How do you think it would be worded best?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.