2015-05-12 83 views
0
M = round(csvread('noob.csv')) 

save projectDAT.dat M -ascii 
load projectDAT.dat 


mat = (projectDAT) 
sum_of_rows(mat) 
plotthegraph 

這是我的主要腳本。我有一個excel文件,它在matlab中打開了一個20 x 20的矩陣。現在我不得不在這個主題中調用一個函數,它將爲我找到一行中的元素的總和並將它們放入列向量中。這裏是我的功能:通過調用函數繪製圖形

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 

我需要繪製使用此列向量的線圖。我應該從主腳本中調用一個函數。該函數應該能夠接受來自sum_of_rows函數的輸入。我試圖這樣做:

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 

雖然它不工作。有人可以幫助我,我真的很感激它。謝謝。

回答

0

你可以做以下襬脫sum_of_rows功能:

sumRow = sum(mat,2); 

第二個參數告知總和添加在矩陣橫行所有列,讓你每一行的總和

要繪製這個向量,你需要將它作爲輸入傳遞給你的函數。此外,如果您不指定變量,matlab會爲您處理x值,正如您在定義x時所做的那樣。你的函數應該是這樣的:

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 

所以你必須調用這個函數通過行的總和:

plotthegraph(sumRow) 
+1

謝謝你這麼多 – Logan

+0

嘿。你的代碼工作得很好。但是當我關閉matlab並再次打開它以再次嘗試代碼時,它會一直說: ???未定義的函數或變量'sumRow'。 – Logan

+0

加載project.dat再次發出sumRow = sum(mat,2);.當matlab關閉時,環境被清除 – brodoll