Create struct before function or in/with function?
Mostrar comentarios más antiguos
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 :-)
3 comentarios
Jan
el 3 de Mayo de 2017
I assume you mean:
function data = myfunction(folder)
data = struct(name,[],data,[])
cd(folder)
data.data = magic(5)
data.name = 'random'
end
Rafi egal
el 3 de Mayo de 2017
@Rafi egal: you should use absolute or relative paths instead of using cd. Beginners like cd because it mimics how they work, but actually it is slower and harder to debug than using proper filepaths.
Respuesta aceptada
Más respuestas (1)
dpb
el 3 de Mayo de 2017
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.
1 comentario
Rafi egal
el 3 de Mayo de 2017
Categorías
Más información sobre Structures en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!