Python/Homework 0

From PrattWiki
Revision as of 01:23, 1 September 2022 by DukeEgr93 (talk | contribs) (Created page with "== Background == This page comes from an assignment Dr. G would give out to classes that have EGR 103 as a pre-requisite to give an idea of what kinds of computational abilit...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Background

This page comes from an assignment Dr. G would give out to classes that have EGR 103 as a pre-requisite to give an idea of what kinds of computational abilities might come into play over the course of the semester. The assignment was not graded, but students were expected to complete it and ask questions about any topics they were unsure of. Given that, it might as well live on Pundit! Both MATLAB and Python solutions are available, though starting in Fall of 2021 the last of the MATLAB EGR 103 students will have generally graduated and so most people will be using Python. If you did not take EGR 103 or CS 101 (i.e. you have never seen Python), there will be some Pundit pages that should help out.

Problems

Linear fit

Many systems you will be learning about have some kind of linear relationship between an applied field and a measured response. This problem explores that for a circuit and the relationship between the voltage across an element and the current through it. There is a link below to data sets for ten experimental runs where a particular voltage was applied to an element and the current through it was measured. Write code that automates the process of

  • Loading data from a file,
  • Determining the line of best fit for the current as a function of the voltage, and
  • Storing the slope and intercept of the fit into arrays called slope and intercept, respectively.

Once all data files are processed, print a table with results of all 10 runs to the screen using scientific notation for all the numbers and making sure the numbers line up under each other. Note that the slopes will generally be positive but the intercepts may be negative.

References

Answers

Your code should end up displaying the following:

     Slope  Intercept
 5.787e+00  1.440e-01
 4.640e+00  3.912e-02
 5.934e+00  1.174e-01
 5.234e+00  9.758e-02
 4.898e+00  1.168e-01
 5.923e+00  1.745e-01
 4.179e+00 -9.780e-02
 5.296e+00  8.575e-02
 5.206e+00  1.369e-01
 5.205e+00  4.678e-02

Solutions

Python

MATLAB
%% Initialize workspace
clear; format short e

%% First line of table
fprintf('%10s %10s\n', 'Slope', 'Intercept')

%% Initialize variables
N = 10;
slope = zeros(N, 1);
intercept = zeros(N, 1);

%% Loop to find, store, and print slope and intercept
for k=1:10
    eval(sprintf('data = load(''file%02.0f.dat'');', k));
    v = data(:, 1);
    i = data(:, 2);
    p = polyfit(v, i, 1);
    slope(k) = p(1);
    intercept(k) = p(2);
    fprintf('%10.3e %10.3e\n', slope(k), intercept(k))
end