MATLAB fprintf function

  • MATLAB
  • Thread starter HAL10000
  • Start date
  • #1
HAL10000
21
0
I'm trying to create a table with three separate columns using fprintf(). The first column consists of a height vector h = 0:500:10000 and the second and third columns are part of the matrix Distance.
I've tried looking online and I can't seem to find a way to make the vector and the matrix to print side by side. There are easier ways to obtain this result but the homework problem is telling me to use fprintf(). Please help.

This is the code for the function:


Code:
%--------------------------------------------------------
function [ Distance ] = dist_func( h , r )
% dist_func This function calculates the distance to the horizon
%from various heights on different planets.
Distance = sqrt((2.*r.*h) + h.^2);
end
%--------------------------------------------------------
... and the program:
Code:
%--------------------------------------------------------
% Homework Problem 1 This program calculates the distance
%to the horizon from different heights on Earth and Mars.
%
% Define the height matrix values in feet.
h = 0:500:10000;
%
% Define the radius values for Earth and Mars in feet.
radius_earth = 3963;
radius_mars = 2108.5;
%
% Define radius matrix in feet
r = [radius_earth;radius_mars];
%
% Create grid containing all height and radius values in feet.
[hg,rg] = meshgrid(r,h);
% Calculate distance for both radii and convert to miles.
Distance = dist_func(hg,rg)*(1/5280);
% Place data into table format
disp('  Height   Distance on Earth    Distance on Mars')
fprintf('%8.2f\n',h); fprintf('%8.2f %8.2f\n',Distance')
The last line is an attempt at making the table.
 
Last edited by a moderator:

Answers and Replies

  • #2
Wrichik Basu
Insights Author
Gold Member
2022 Award
2,021
2,152
Use a for loop to print the matrix elements. For each print statement, separate the matrix entries by tab, \t.
 

Suggested for: MATLAB fprintf function

  • Last Post
Replies
6
Views
86
  • Last Post
Replies
4
Views
204
Replies
1
Views
734
  • Last Post
Replies
2
Views
614
  • Last Post
Replies
2
Views
757
  • Last Post
Replies
1
Views
644
  • Last Post
Replies
2
Views
456
Replies
1
Views
445
Replies
10
Views
1K
  • Last Post
Replies
4
Views
2K
Top