How do I pass by reference, a structure to a function (an .m file) in an argument list?
조회 수: 8 (최근 30일)
이전 댓글 표시
I am calling an .m file function which as format: "function[] = myFunctionName(structA,structB)" in top line, followed by lines of code and completed with an end statement. I am sendiing the function very large data entities,...huge arrays for example. And I want to edit (change values) these arrays in the function. So when I call this function in the body of the program,...ie myFunctionName(hugeStructure) I suspect hugeStructure will be sent as a copy (value) which will take a lot of memory and not change the value in the calling routine. If hugeStructure is sent by reference (ie a pointer), then only the structure address will be sent which cuts way down on overhead and memory in addition to allowing me to change the structure in the calling routine. Q1: is there a way I can force hugeStructure be sent via reference? Q2: If hugeStructure is in both the input list and output list, will it be sent by reference?
Function main:
function[] = main()
inStruct.Val1 = 5;
inStruct.Val2 = 105;
inStruct.Val3 = 505;
simpleMath2(inStruct);
aaa = 5;
end
Calls function simplemath2:
function[] = simpleMath(hugeStructure)
hugeStructure.Val1 = hugeStructure.Val1 + 50;
hugeStructure.Val2 = hugeStructure.Val2 + 50;
hugeStructure.Val3 = hugeStructure.Val3 + 50;
end
The values in function main do not change after calling simplemath2.
댓글 수: 0
채택된 답변
Sean de Wolski
2022년 5월 3일
Author a simple handle class that has the structure as a property
classdef referenceStruct < handle
properties
S struct
end
end
Now use this.
rs = referenceStruct;
rs.S.Var1 = pi;
somefunction(rs)
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!