简体   繁体   English

使用MATLAB中的索引将多个函数输出分配给向量

[英]Assign multiple function outputs to a vector using indexing in MATLAB

I have a simple MATLAB function outputting multiple variables: 我有一个简单的MATLAB函数输出多个变量:

function [a,b] = MultipleOutputs()
a = 6;
b = 8;
end

I want to assign the two output variables to 2 certain elements in an existing vector: 我想将两个输出变量分配给现有向量中的2个特定元素:

x = ones(1,4);
x(2:3) = MultipleOutputs()

However, this gives me: 但是,这给了我:

x =

     1     6     6     1

Instead of: 代替:

x =

     1     6     8     1

I have had this problem in multiple cases, was never able to find the solution. 我在很多情况下都遇到过这个问题,但从未找到解决方案。

You have 2 choices: 您有2个选择:

Concatenate the vectors after outputting them separately 分别输出向量后将它们连接起来

[a,b] = MultipleOutputs();
x = ones(1,4);
x(2:3) = [a,b];

concatenate the vectors before outputting them 在输出之前将向量连接起来

function a = MultipleOutputs()
    a(1) = 6;
    a(2) = 8;
end

x(2:3) = MultipleOutputs();

when you run MultipleOutputs() like that in another function, it only outputs only the first element, which in this case is a . 当您像在另一个函数中那样运行MultipleOutputs() ,它仅仅输出第一个元素,在这种情况下为a

So eventually your statement x(2:3) = MultipleOutputs() is equivalent to x(2:3) = 6 . 因此最终,您的语句x(2:3) = MultipleOutputs()等效于x(2:3) = 6

A simple fix would be to extract all the elements: 一个简单的解决方法是提取所有元素:

[a,b] = MultipleOutputs();
x(2:3) = [a b];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM