How do I put variable values into a text string in MATLAB?

前端 未结 5 1166
终归单人心
终归单人心 2021-02-13 19:17

I\'m trying to write a simple function that takes two inputs, x and y, and passes these to three other simple functions that add, multiply, and divide

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-13 20:10

    You can use fprintf/sprintf with familiar C syntax. Maybe something like:

    fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)
    

    reading your comment, this is how you use your functions from the main program:

    x = 2;
    y = 2;
    [d e f] = answer(x,y);
    fprintf('%d + %d = %d\n', x,y,d)
    fprintf('%d * %d = %d\n', x,y,e)
    fprintf('%d / %d = %f\n', x,y,f)
    

    Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:

    function result=answer(x,y)
    result(1)=addxy(x,y);
    result(2)=mxy(x,y);
    result(3)=dxy(x,y);
    

    and call it simply as:

    out = answer(x,y);
    

提交回复
热议问题