此 MATLAB 函数返回结果向量
如果我在 MATLAB 中有一个函数,并且在其中有一个计算两个变量的循环,类似于:
for index = 1:1000,
var1 = 0.0;
var2 = zeros(size(someMatrix));
...
%some calculus...
...
end
我如何定义函数来返回这两个变量,但它们在循环中遭受的所有更改,例如
var1 = [1, 3, 5, 7]
var2 = some matrix,
因此函数返回单个值。如何返回从循环中获得的结果向量?
If I have a function in MATLAB, and within it I have a loop, that calculates two variables, something like:
for index = 1:1000,
var1 = 0.0;
var2 = zeros(size(someMatrix));
...
%some calculus...
...
end
How do I define the function to return those two variables, but with all changes they suffered while in the loop, like
var1 = [1, 3, 5, 7]
var2 = some matrix,
So instead the function returns a single value. How do I return a vector of results, gotten from the loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我知道你在更高层次上想做什么,我也许可以给你更好的建议。当我读到这个问题时,我问自己“他为什么要这么做?”。很可能有更好的方法来完成您想做的事情。
话虽这么说,我认为你正在尝试做这样的事情。
我并不是说这个函数是完成您想要做的事情的好方法,但我认为它完成了这项工作。如果确实如此,请发表评论,然后也许其他人可以过来告诉您如何更有效/更安全地做到这一点。
我提供的解决方案很容易出现问题。如果您的变量在同一循环中更改两次,您是否想看到这一点?如果您更新矩阵的一个元素,您是否想看到这一点?您的变量可以改变循环中的维度或类型吗?如果变量在循环中没有更改值,您是否可以包含这些值?
也许这个解决方案更适合您想要做的事情:
If I knew what you were trying to do at a higher level I might be able to give you better advice. When I read this question I ask myself "Why would he want to do that?". Chances are there is a much better way to do what you are trying to do.
That being said, I think you are attempting to do something like this.
I'm not saying that this function is a good way of doing what you are trying to do, but I think it accomplishes the job. If it does, leave a comment, then maybe someone else can swing by and tell you how to do it more efficiently/safer.
The solution I provided is going to be prone to problems. If your variable changes twice in the same loop, do you want to see that or not? If you update one element of a matrix, do you want to see that or not? Can your variables change dimensions or types in the loop? If the variables don't change values in the loop, can you include those values anyways?
Perhaps this solution would work better for what you are trying to do:
然后你可以像这样调用该函数
You can then call the function like this