在Matlab中循环函数

时间:2016-08-31 09:14:27

标签: matlab function loops

这里的新手总数。我在循环创建我已创建的功能时遇到问题。我在复制代码时遇到了一些问题,但我会对其进行一般性的了解:

function[X]=Test(A,B,C,D)

other parts of the code
.
.
.


X = linsolve(K,L) 
end

其中K,L是从4个变量A,B,C,D

得到的其他矩阵

问题是每当我执行Test(1,2,3,4)函数时,我只能得到一个答案。我试图为一个变量循环这个过程,保持其他3个变量不变。

例如,我想获得A = 1:10的答案,而B = 2,C = 3,D = 4

我已经尝试了以下方法但它们无效:

Function[X] = Test(A,B,C,D)
for A = 1:10

other parts of the code...
X=linsolve(K,L)
end

每当我键入命令Test(1,2,3,4)时,它只给我输出Test(10,2,3,4)

然后我在某个地方读到你必须从其他地方调用该函数,所以我将Test函数编辑为Function [X] = Test(B,C,D)并将A out留在可以在另一个中分配的位置脚本例如:

global A
for A = 1:10
    Test(A,2,3,4)
end

但这也会产生错误,因为测试功能需要定义A。因此,我有点迷失,似乎无法找到有关如何做到这一点的任何信息。非常感谢我能得到的所有帮助。

干杯球员

2 个答案:

答案 0 :(得分:0)

我认为这是你正在寻找的东西:

A=1:10;    B=2;    C=3;    D=4;
%Do pre-allocation for X according to the dimensions of your output
for iter = 1:length(A)
    X(:,:,iter)= Test(A(iter),B,C,D);
end
X

,其中

function [X]=Test(A,B,C,D)
%other parts of the code
X = linsolve(K,L) 
end

答案 1 :(得分:0)

试试这个:

function X = Test(A,B,C,D)
% allocate output (it is faster than changing the size in every loop)
X = {};
% loop for each position in A
for i = 1:numel(A);
    %in the other parts you have to use A(i) instead of just A
    ... other parts of code
    %overwrite the value in X at position i
    X{i} = linsolve(K,L);
end
end

并使用Test(1:10,2,3,4)

运行它

要回答以前出了什么问题: 当您使用&= 39; A = 1:10'你覆盖传递给函数的A(所以函数会忽略你传递给它的A),并且在每个循环中你覆盖在前一个循环中计算的X(这就是为什么你只能看到答案为A = 10 )。 如果您创建了一个名为Test.m的文件,并且函数X =(A,B,C,D)作为文件中的第一个代码,则第二次尝试应该有效。虽然全球任务是不必要的。事实上,我强烈建议你不要使用全局变量,因为它变得非常混乱非常快。

相关问题