How do I use specific columns from a csv file
Show older comments
Hi, I have a csv file and I am trying to use specific columns to input into a function. Below is the code that I have so far where FVC and Height are the names of two of the columns from my csv data.
%% Load data
fvc = readtable("fvc-2022.csv");
%% Fit linear model
fitLinearModel(FVC, Height)
btw, 'fitLinearModel' is the function that I am using and I have attached the csv data set. I know that the 'FVC, Height' part of the code is incorrect so I was wondering what the right code is to add in here.
Thanks.
Accepted Answer
More Answers (1)
Image Analyst
on 5 Sep 2022
0 votes
It's not finding your file. Your file lives in a different folder than your script, and it is also not on the search path. Use fullfile to specify the full path and base file name of your file.
6 Comments
Declan
on 5 Sep 2022
Image Analyst
on 5 Sep 2022
MATLAB is case sensitive so FVC would be a different variable than fvc. Choose one or the other. Be consistent in your capitalization.
Declan
on 5 Sep 2022
Image Analyst
on 5 Sep 2022
What toolbox is fitLinearModel() in? Whatever it is, I don't have it. Plus you didn't define Height. What kind of model do you want to fit? Do you have a formula for it?
Declan
on 5 Sep 2022
Image Analyst
on 5 Sep 2022
Try this:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 15;
t = readtable('fvc-2022.csv')
% Fit line through Heights
x = t.FVC;
y = t.Height;
[intercept, slope, resVar] = fitLinearModel(x,y)
% Fit line through Heights
x = t.FVC;
y = t.Weight;
[intercept, slope, resVar] = fitLinearModel(x,y)
function [intercept, slope, resVar] = fitLinearModel(x,y)
%intercept
P = polyfit(x,y,1);
intercept=P(2);
%slope
slope=P(1);
%resVar
A = [ones(numel(x),1), x(:)];
b = y(:);
c = A\b;
format long
resVar=var(y-(c(1)+c(2)*x))*(numel(x)-1)/(numel(x)-2);
end
Categories
Find more on Creating, Deleting, and Querying Graphics Objects 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!