简体   繁体   中英

How can I pass a vector as a function's argument in MATLAB?

I have a function that generates test data,

function [A B] = generate_test_data()

    A = linspace(0.1, 15, 400)';
    eps = (0.2*rand(400,1)) - 0.1;
    B = sin(A) ./ A - eps;

end

I have another function that writes a 2-col matrix into a text file,

function write_to_file(file_name, A, B)
    fid = fopen(file_name,'w');
    fprintf(fid, '%f\t%f \n', [A B]');
    fclose(fid);
end

Now, I want to use those function as follows,

write_to_file('test_data.txt', generate_test_data());

But, it is generating the following error,

??? Input argument "B" is undefined.

Error in ==> write_to_file at 7 fprintf(fid, '%f\\t%f \\n', [AB]');

what modifications can I make?

You defined write_to_file to take three arguments, but you are calling it with two.

You can initialize A and B beforehand and then pass it to the function as follows:

[A B] = generate_test_data();
write_to_file('test_data.txt', A, B);

(Maybe there is a one-liner alternative to this.)

You can also set the function to take the second argument as a cell, which has members A and B , in this case you can define your functions as follows:

function [C] = generate_test_data()
    A = linspace(0.1, 15, 400)';
    eps = (0.2*rand(400,1)) - 0.1;
    B = sin(A) ./ A - eps;
    C = {A B};
end

and

function write_to_file(file_name, C)
    A = C{1}; B = C{2};
    fid = fopen(file_name,'w');
    fprintf(fid, '%f\t%f \n', [A B]');
    fclose(fid);
end

then you call the function as you do now, ie write_to_file('test_data.txt', generate_test_data()); should work in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM