如何在矢量中获得多个输出的函数? [英] How to get multiple outputs of a function in a vector?

查看:104
本文介绍了如何在矢量中获得多个输出的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数,其输出是两个实数a和b,

我想得到矢量v中的所有输出结果
v = function( c)不做我想要的,v只是'a'。
当然,我可以做v = [a,b]。
但是有问题的函数是ND数组的ind2sub,所以它提供了n个输出,我想直接在矢量中使用。



是否有如何做到这一点?
非常感谢!

解决方案

您可以使用单元格数组和一个逗号分隔的列表,如下所示:

  X = cell(N,1); 
[X {:}] = function(C);

语法 X {:} 在事实上扩展为 [X {1},X {2},...] ,它为您的函数提供了一个有效的接收器。因此,每个输出变量都将存储在 X 中的不同单元格中。



如果每个输出变量是一个标量,你可以通过使用又一个以逗号分隔的列表展开将单元格数组展开为一个向量:

  v = [ X{:}]; 


Say I have a function whose outputs are two reals a and b

[a,b]=function(c)

I'd like to get all the outputs in a vector v. v=function(c) doesn't do what I want, v is 'a' only. Of course here I could do v=[a,b]. But the function in question is ind2sub for a N-D array so it gives n outputs that I'd like to have in a vector directly.

Is there a way to do it? Thanks very much!

解决方案

You can use a cell array and a comma-separated list like so:

X = cell(N, 1);
[X{:}] = function(C);

The syntax X{:} is in fact expanded to [X{1}, X{2}, ...], which provides a valid sink for your function. As a result, each output variable will be stored in a different cell in X.

If each output variable is a scalar, you can flatten out the cell array into a vector by using yet another comma-separated list expansion:

v = [X{:}];

这篇关于如何在矢量中获得多个输出的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆