我已经在大学的MATLAB中编写了一个代码,我被告知缩进很重要,它导致我在8中失去了3分。缩进不仅仅是“风格”吗?
代码如下:
function[pp,pb,pd]=demopoly(fname,N)
%The function reads the data from the file and computes the coefficients of a polynomial of degree N of three polynomials pp, pb, and pd that best fit the population, births and deaths in the data.
%The function returns the three variables pp, pb and pd in this order.
C=csvread(fname);
pp=polyfit(C(:,1),C(:,2),N);
pb=polyfit(C(:,1),C(:,3),N);
pd=polyfit(C(:,1),C(:,4),N);
end
有人能告诉我压痕应该在哪里发生吗?
答案 0 :(得分:6)
nomatterssuchaspunctuationandindentationarenotjustmattersofstyletheyareanessentialaidtohumancomprehensionofwrittentextwhetherprosepoetryorcodeicouldgoonbutwont
答案 1 :(得分:4)
另一方面是过度分析
No, matters such as
punctuation
and indentation
are not just matters of style
they are an essential aid to
human comprehension of
written text whether prose
poetry or
code
i could go on
but wont
答案 2 :(得分:2)
缩进只是 Ctrl + A 和 Ctrl + I 。似乎很难?其他答案指出为什么压痕很重要。关于缩进应该出现的问题,事实是 你所展示的代码中没有缩进问题 。
如果我不得不为你所展示的代码削减你的分数,我会切入:
答案 3 :(得分:2)
虽然Matlab代码对压力不敏感(例如,Python不同),但为了提高代码的可读性而使用缩进非常重要,而且maintainability。
如果您在编写代码时懒得手动缩进代码,Matlab会为您提供一个Smart Indent
函数,您可以在文件完成后应用它们(更多信息here)。如果您对CTRL+A
CTRL+I
过于懒惰,可以编写一个小的“疯狂批处理脚本”,将Smart Indent
应用于位于其中的所有.m
文件特定文件夹:
files = dir(fullfile(folder,'*.m'));
for i = 1:numel(files)
file_name = files(i).name;
file_path = fullfile(folder,file_name);
file_handle = matlab.desktop.editor.openDocument(file_path);
file_handle.smartIndentContents()
file_handle.save()
file_handle.close()
end
这是我如何格式化(并优化一点)你的功能:
% The function reads the data from the file and computes
% the coefficients of a polynomial of degree N of three
% polynomials (pp, pb, and pd) that best fit the population,
% births and deaths in the data.
% The function returns the three variables pp, pb and pd
% in this order.
function [pp,pb,pd] = demopoly(fname,N)
C = csvread(fname);
C_1 = C(:,1);
pp = polyfit(C_1,C(:,2),N);
pb = polyfit(C_1,C(:,3),N);
pd = polyfit(C_1,C(:,4),N);
end