MATLAB: How to structure array to serve as input parameter for function and then display in sprintf

MATLABsprintf array output

This question builds on my last one. Consider that I use arrays of X and Y values for two points in order to find the slopes of lines on those points:
formatSpec = 'The slope of a line containing points(%i, %i) and (%i, %i) is %8.4f\n';
aX1 = [1, 23];
aY1 = [1, 12];
aX2 = [2, 8];
aY2 = [2, 0];
clc;
m1 = f_GetSlope(aX1, aY1, aX2, aY2);
sprintf(formatSpec, aX1, aY1, aX2, aY2, m1)
I'm now getting the correct slopes. But look what sprintf does with the output:
m1 = 1.0000 0.8000
ans =
The slope of a line containing points(1, 23) and (1, 12) is 2.0000
The slope of a line containing points(8, 2) and (0, 1) is 0.8000
sprintf is not using the first value of each coordinate array and the first value of the answer array for the variables in the format, and then doing the same for the second.
Rather, sprintf just plugs the first and second value of the first input array, the first and second value of the second input array, and the first value of the third input array into the first output line.
Then it takes the second value of the third array, the two values from the fourth array, and the two values from the answer array, and uses those in the second output line.
What a mess! Suggestions?

Best Answer

SPRINTF and FPRINTF are repeating formatSpec as many times as needed to display the content of the arguments that follow. To illustrate:
>> fprintf('Value = %d\n', [1, 2, 3]) % Single %d leads to 3 outputs.
Value = 1
Value = 2
Value = 3
so it's not always obvious how to pass multiple arrays and obtain an output which corresponds to what we want (in your case, you would have to concatenate all the arrays I guess and pass them column by column instead of row by row) .. however, you could go for a loop here:
formatSpec = 'The slope of a line containing points(%i, %i) and (%i, %i) is %8.4f\n' ;
for k = 1 : numel(aX1)
fprintf(formatSpec, aX1(k), aY1(k), aX2(k), aY2(k), m1(k)) ;
end