如何通过引用传递矩阵或获取函数的返回值 [英] How to pass matrix by reference or get the return value of function

查看:108
本文介绍了如何通过引用传递矩阵或获取函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为current_load的1 x 118矩阵,需要定期更新.该矩阵位于Matlab的主工作区中(如下面的代码所示).

I have a 1 x 118 matrix called current_load that I need to update periodically. This matrix resides in the main workspace of Matlab (as shown in the code bellow).

current_loads = zeros(1, 118); 
for col=1:118
    current_loads(1,col)=10; %// Initially give all nodes a current load of 10    
end
recursive_remove(current_loads); %calling function

此矩阵将传递给函数调用recursive_remove(如下所示的 ).

This matrix will be passed to a function call recursive_remove (shown bellow).

function updater = recursive_remove( current_load )
     current_load(1,3) = 2.6; %// This update can't be seen from main ??
     %this function will be called recursively later
end

但是我从函数对该current_load矩阵进行的任何更新,都不会得到更新,因为我不知道如何通过引用传递它.

But whatever updates I do to this current_load matrix from the function, it will not get updated since I don't know how to pass it by reference.

我是Matlab的新手.如果您能举例说明如何处理此问题,我将不胜感激

I am new to Matlab. I would greatly appreciate if you can show with an example how to handle this

推荐答案

如何在Matlab中通过引用传递参数" 您可以解决通过引用传递参数的问题

"How to pass parameter by reference in Matlab" You can solve your problem passing your arguments by reference

您需要一个句柄类

句柄类

与其他对象共享引用的对象

Objects that share references with other objects

这是使用以下代码创建一个名为HandleObject.m的文件:

this is, create a file called HandleObject.m with this code:

classdef HandleObject < handle
   properties
      Object=[];
   end

   methods
      function obj=HandleObject(receivedObject)
         obj.Object=receivedObject;
      end
   end
end

然后您可以执行类似的操作

Then you can do something like this

Object = HandleObject(your matrix)
yourFunction(Object)

在函数内部

function yourFunction(myObject)
    myObject.object = new matrix;
end

这样一来,您可以通过引用获得某种通过,并避免程序中出现很多副本.

With that you can achieve some kind of pass by reference and avoid getting a lot of copies trought your program.

这篇关于如何通过引用传递矩阵或获取函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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