我正在尝试从函数中返回所有for循环的值,而且我需要在函数外部调用它们。但是我只获得了for循环的最后一行,我还需要for循环的先前结果。 这是我的代码
i=input('Enter a start row: ');
j=input('Enter a end row: ');
c=input('Enter classifier variable column number:')
search= importfiledataset('search-queries-features.csv',i,j);
[n,p]=size(search);
if j>n
disp('Please enter a smaller number!');
end
[D1,Eps1]=findD(i,j,c,search);
disp(D1);
disp(n1);
function [D1,Eps1] = findD(i,j,c,search) %Find D vlaues with for loop for each classification value
for numOfClassifier = 1 : 100
a = search(search(:,c)==numOfClassifier,:) ;
q1 = a(all(~isnan(a),2),:); % for nan - rows
D1 = a(:,all(~isnan(a))) % for nan - columns WE FIND D1
n1=size(D1,1) %number of record belongs to classification
sampleSpace = size(search,1) %sample space of the priop probability(#of c1 + #of c2 .... cn)
pc1 = n1/sampleSpace %prior probability of the n
mu1 = mean(D1) %mean of D1
Z1 = D1 - mu1 % centered data of D1
Eps1 = (1/n1)*(transpose(Z1)*Z1) %covariance matrix if Z1
numOfClassifier = numOfClassifier + 1;
if search(:,c) ~= numOfClassifier
break
end
end
end
我需要退回
我想返回for循环的全部值,但最终只能得到最后一行的值。
答案 0 :(得分:3)
您可以将迭代结果存储在cell array中,并返回单元格数组:
函数返回两个单元格数组(我将它们分别命名为allD1
和allEps1
):
function [allD1, allEps1] = findD(i,j,c,search)
在循环之前将单元格数组初始化为空单元格:
allD1 = {};
allEps1 = {};
在单元格数组的末尾添加D1
和Eps1
(将其放在break
语句的行之前):
allD1{end + 1} = D1;
allEps1{end + 1} = Eps1;
这是修改后的代码:
i=input('Enter a start row: ');
j=input('Enter a end row: ');
c=input('Enter classifier variable column number:')
search= importfiledataset('search-queries-features.csv',i,j);
[n,p]=size(search);
if j>n
disp('Please enter a smaller number!');
end
[D1,Eps1]=findD(i,j,c,search);
disp(D1);
disp(n1);
function [allD1, allEps1] = findD(i,j,c,search) %Find D vlaues with for loop for each classification value
%Initialize empty cell arrays
allD1 = {};
allEps1 = {};
for numOfClassifier = 1 : 100
a = search(search(:,c)==numOfClassifier,:) ;
q1 = a(all(~isnan(a),2),:); % for nan - rows
D1 = a(:,all(~isnan(a))) % for nan - columns WE FIND D1
n1=size(D1,1) %number of record belongs to classification
sampleSpace = size(search,1) %sample space of the priop probability(#of c1 + #of c2 .... cn)
pc1 = n1/sampleSpace %prior probability of the n
mu1 = mean(D1) %mean of D1
Z1 = D1 - mu1 % centered data of D1
Eps1 = (1/n1)*(transpose(Z1)*Z1) %covariance matrix if Z1
%Add D1 (and Eps1) to the end of the cell array
allD1{end + 1} = D1;
allEps1{end + 1} = Eps1;
numOfClassifier = numOfClassifier + 1;
if search(:,c) ~= numOfClassifier
break
end
end
end
单元格数组比数组更通用-单元格可以存储不同类型和形状的值,而不是所有元素都必须为同一类型的数组。
在您的情况下,多维数组可能适合,但更加令人困惑。
对于单元格数组,每个单元格都包含匹配迭代的结果。
例如:allD1{3}
在第三次迭代中保存D1
的值。