As you can see it is saving my values from my function pol2rect as a 5x1 double and I am trying to print out my values of these doubles as columns into a new file but instead of columns they are printing in the next available spot.
Format printing problem with doubles printing in rows when I am looking for columns.
18 views (last 30 days)
Show older comments
prompt = {'Theta 1', 'Theta 2', 'Theta 3', 'Theta 4', 'Theta 5'};
prompt2 = {'Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5'};
dlgtitle = '\Theta values 0 -> 260';
dlgtitle2 = 'Radius values 2-20';
t = inputdlg(prompt, dlgtitle);
r = inputdlg(prompt2, dlgtitle2);
radius = cellfun(@str2num, r);
theta = cellfun(@str2num, t);
[x,y] = Pol2Rect(radius, theta);
fileName = 'prog9_OUTPUT_JMG.txt';
fileID = fopen(fileName, 'w');
header1 = 'Polar Coordinates';
header2 = 'Rectangular Coordinates';
header3 = 'Table 1 Polar Coordinates Converted to Rectangular Coordinates';
%prints out the formatted table
fprintf(fileID, '\t%s\n\n', header3);
fprintf(fileID,'%s\t\t\t\t%s\n\n',header1, header2);
fprintf(fileID,'R(meters) Theta(degrees) x(meters) y(meters)\n');
fprintf(fileID,'%5.1f\t%5.1f\t\t\t\t%5.1f\t%5.1f \n', radius, theta, x, y);
fclose(fileID);
Accepted Answer
Voss
on 4 Nov 2024 at 19:30
fprintf prints the values in the order you supply them; in this case that means all elements of radius are printed then all elements of theta and so on.
But you want to print radius(1), theta(1), x(1), y(1), radius(2), theta(2), etc., so what you can do is put those 4 vectors into a matrix and call fprintf with the matrix as the data argument. When given a matrix, fprintf will go down the first column first, then move to the second column, etc., so to get it to print by row instead, merely transpose the matrix.
Here's an example showing the problem and the solution:
radius = [2;3;4;5;6];
theta = [30;40;50;60;70];
[x,y] = pol2cart(radius,theta); % I don't know what Pol2Rect is, but it doesn't matter for this
whos radius theta x y % the variables are all column vectors, same as yours
fileID = 1; % print to command window, for demonstration
fprintf(fileID,'%5.1f\t%5.1f\t\t\t\t%5.1f\t%5.1f \n', radius, theta, x, y);
fprintf(fileID,'%5.1f\t%5.1f\t\t\t\t%5.1f\t%5.1f \n', [radius, theta, x, y].' );
3 Comments
More Answers (0)
See Also
Categories
Find more on LaTeX in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!