Create struct before function or in/with function?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi everyone! I got a small questen regarding "what is better programming":
--------------------------------------
I could either code in the main:
mystruct = struct(name,[],data,[])
myfunction(folder,mystruct)
and in the function:
function mystruct = myfunction(folder,mystruct)
cd(folder)
mystruct.data = magic(5)
mystruct.name = 'random'
end
--------------------------------------
or I could in the main:
mystruct = myfunction(folder)
and in the function:
function mytruct = myfunction(folder)
mystruct = struct(name,[],data,[])
cd(folder)
mystruct.data = magic(5)
mystruct.name = 'random'
end
--------------------------------------
Is there a programming reason why one of this variation has to be picked? I think (I might be wrong) in C++ you have to allocate the struct before going into the function, but we are in matlab here :-D
Thanks for your help :-)
채택된 답변
Jan
2017년 5월 3일
편집: Jan
2017년 5월 3일
The 2nd version is nicer, in my opinion:
- Version 1 receives a struct with the wanted fields, which have been create in the caller, and inserts the data.
- Version 2 creates a struct with the wanted fields.
Version 2 is easier to explain. If you want to expand the struct later, you have to edit 2 function with version 1, but 1 function only with version 2.
By the way: cd(folder) is a bad style in both cases. Absolute path names are much saver, because a GUI or timer callback could modify teh current folder unexpectedly.
댓글 수: 0
추가 답변 (1개)
dpb
2017년 5월 3일
In Matlab, you can go even further and
function mytruct = myfunction(folder)
cd(folder)
mystruct.data = magic(5)
mystruct.name = 'random'
end
and allocation occurs on the fly. I don't know if there's a significant performance penalty this way (or vice versa if there's a speed advantage in having an empty structure with the two names first), but my guess would be "probably not", there will be a reallocation anyway since the declaration is null.
It's not the same as allocating an array and "growing" elements iteratively which is slow owing to reallocation and copy as the full structure content is generated and stored in the assignment.
It'd take some testing to ascertain that behavior for certain.
Either way, in Matlab since all allocations are dynamic, the second is the more "Matlab-y like" paradigm imo, as Jan notes.
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!