user2010340
user2010340

Reputation: 13

creating classes in matlab or converting c code in matlab

how can i create classes in matlab....please explain using example.

i want to create class operation in that class there should be 3 functions add,multiply,minus.... and i want to access it through .m file

i am posting rough c code and i want this to be done in matlab

class operation
{
    public:

    function add(int a,int b)
    {
        return(a+b);
    }

    function minus(int a,int b)
    {
        return(a-b);
    }
}

void main()
{
    int a,b;
    operaion o;
    cout<<o.add(2,4)<<endl;
    cout<<o.minus(3,5);  

    return 0;


}

Upvotes: 0

Views: 142

Answers (2)

alrikai
alrikai

Reputation: 4194

You can put this as your class in an .m file (e.g. operation.m)

classdef operation
    methods
        function c = add(obj, a, b)
            c = a + b;
        end
        function c = minus(obj, a, b)
            c = a - b;
        end
        function c = multiply(obj, a, b)
            c = a * b;
        end

        %.... add whatever other functions

    end
end

Then you can use it as such:

obj = operation;
obj.add(1,2)
obj.minus(1,2)
obj.multiply(1,2)

With that said, I'd highly recommend that you read the matlab documentation for this, as it's quite thorough. You can start here: http://www.mathworks.com/help/matlab/object-oriented-programming.html

Upvotes: 2

Mayank Jain
Mayank Jain

Reputation: 2564

Heres one example taking the C code you attached in question.For simplicity the name of files are kept same as function name in C

Make three files as shown below :

add.m

function [result]=add(a,b)

result=a+b;

minus.m

function [result]=diff(a,b)

result=a-b;

main.m

a=input('Enter one number:');

b=input('Enter Second number:');

add_res=add(a,b)

diff_res=diff(a,b)

Upvotes: 0

Related Questions