Matlab 通过调用函数绘制图形

Matlab 通过调用函数绘制图形,matlab,plot,Matlab,Plot,这是我的主要剧本。我有一个excel文件,它在matlab中打开了一个20 x 20的矩阵。现在我必须在这个主脚本中调用一个函数,它将为我找到一行中元素的总和,并将它们放入一个列向量中。以下是我的功能: M = round(csvread('noob.csv')) save projectDAT.dat M -ascii load projectDAT.dat mat = (projectDAT) sum_of_rows(mat) plotthegraph function plotth

这是我的主要剧本。我有一个excel文件,它在matlab中打开了一个20 x 20的矩阵。现在我必须在这个主脚本中调用一个函数,它将为我找到一行中元素的总和,并将它们放入一个列向量中。以下是我的功能:

M = round(csvread('noob.csv'))

save projectDAT.dat M -ascii
load projectDAT.dat


mat = (projectDAT)
sum_of_rows(mat)
plotthegraph
function plotthegraph(~)

% Application for plotting the height of students
choice = menu('Choose the type of graph', 'Plot the data using a line plot',         'Plot the data using a bar plot');
if choice == 1
   plot_line(sum_of_rows) 
y = sum_of_rows
x = 1:length(y)
plot(x,y)
title('Bar graph')
xlabel('Number of characters')
ylabel('Number of grades')

elseif choice == 2
   plot_bar(sum_of_columns)
end
我需要用这个列向量绘制一个折线图。我应该从主脚本调用一个函数。该函数应该能够从该行和函数获取输入。我试着这样做:

function sumRow = sum_of_rows(mat)
[m n] = size(mat);

sumRow = zeros(m,1);
for i = 1:m;
    for j = 1:n;
        sumRow(i) = sumRow(i) + mat(i,j);
    end
end
vec = sumRow;
end

不过,这是行不通的。谁能帮我一下,我会非常感激的。谢谢。

您可以执行以下操作来删除行和函数:

M = round(csvread('noob.csv'))

save projectDAT.dat M -ascii
load projectDAT.dat


mat = (projectDAT)
sum_of_rows(mat)
plotthegraph
function plotthegraph(~)

% Application for plotting the height of students
choice = menu('Choose the type of graph', 'Plot the data using a line plot',         'Plot the data using a bar plot');
if choice == 1
   plot_line(sum_of_rows) 
y = sum_of_rows
x = 1:length(y)
plot(x,y)
title('Bar graph')
xlabel('Number of characters')
ylabel('Number of grades')

elseif choice == 2
   plot_bar(sum_of_columns)
end
第二个参数告诉sum按行添加矩阵中的所有列,从而得到mat中每行的总和

要绘制此向量,需要将其作为输入传递给函数。另外,如果您不指定变量,matlab会为您处理x值,就像您在定义x时手动执行的一样。您的函数如下所示:

sumRow = sum(mat,2);
因此,您必须调用此函数来传递行的总和:

function plotthegraph(sum_of_rows)

% Application for plotting the height of students
prompt='Type 1 for line plot, 2 for bar';
choice=input(prompt)
if choice == 1
    plot(sum_of_rows)
    title('Line graph')
    xlabel('Number of characters')
    ylabel('Number of grades')
elseif choice == 2
    bar(sum_of_rows)
end
end

嘿你的代码运行得很好。但是,当我关闭matlab并再次打开它以再次尝试代码时,它一直在说:???未定义的函数或变量“sumRow”。再次加载project.dat发出sumRow=sum(mat,2);。当matlab关闭时,环境是透明的,我正在运行整个脚本。它展示了到那一点的一切。当我第一次这样做时,我保留了函数sum_of_rows,而不是sumRow=sum(mat,2),它工作得很好,给了我图表和所有东西。第二次,它就是做不到。根据说明,我还必须使用for循环。有什么想法吗?既然你删除了sum(mat,2),确保你把sumRow=sum\u of_rows(mat);在您的第一段代码中,它与for循环一起工作!否则,当您调用plotthegraph(sumRow)时,它会给您带来您经常提到的错误。我真的很感激。