new to Matlab, first code questions and critique

2 次查看(过去 30 天)
I started using Matlab not quite a week ago... I was super excited when I got this code below to work, but when I see how efficient the code can be, and realize I don't know what I don't know, and believe this to be a great community, I figured I'd see if I could get some feedback as to how this code could be better, more efficient, and perhaps not break foundational rules of coding I'm not actually familiar with... thanks, Hew
clear data ii kk mm
data=p552r2_tnL; % I have p552r1, p552r2...p552rn but can't seem to index them so I type the names in here,
% they aren't always the same length
[m,n] = size (data);
regr_valuesn = zeros (14,2);
% I'm using this n at the end to indicate I'd like to index as the file name above indexes, but I couldn't get
% it to do it... I use this n at the end of vector names used below as well
ii = 1;
kk = 1;
for ii=1:14
regr_valuesn (kk,1:2)=polyfit(data(:,1),data(:,2+3*ii),1); % my y values start at column 5 and skip every 3
kk = kk + 1;
end
% polyfit gives p1(1) and p1(2) so I stored it in regn_valuesn in two columns, but though there might be a way
% to get this into one cell(?)
% basic regression code I borrowed off youtube to create the code below
%yfit = p1(1) * x + p1(2);
%yresid = y - yfit;
%ssresid = sum(yresid.^2);
%sstotal = length(y)-1) * var(y);
%rsq = 1 - ssresid/sstotal;
% I only want the regression values and r-squared, but end up creating all the other stuff in the
% workspace as well...
jj = 1;
mm = 1;
for jj=1:14
yfitn (:,jj) = regr_valuesn(jj,1)*data(:,1) + regr_valuesn (jj,2);
yresidn (:,jj) = data(:,2+3*mm) - yfitn(:,jj);
ssresidn (:,jj) = sum(yresidn(:,jj).^2);
sstotaln (:,jj) = (length(data)-1) * var(data(:,2+3*mm));
rsqn (:,jj) = 1 - ssresidn(:,jj)/sstotaln(:,jj);
mm = mm +1;
end
  1 个评论
Stephen23
Stephen23 2018-9-25
"I have p552r1, p552r2...p552rn but can't seem to index them so I type the names in here"
The most important question is: how did you get those variables into the workspace? Once you fix the data importation then you could easily write the rest of your code to loop over it.
Typing a new name each time you run the code is not a very efficient use of your time, nor is "indexing" a good idea. In fact, dynamically accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
A much more efficient solution is to use indexing with one array (which could be ND numeric, cell, table, structure, etc.).

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by