FUCK YEAH RECURSION

A Function to Un-Nest Nested Structures in MATLAB

So I’m flying back from Shanghai right now, (youalreadyknow it’s business class) and I decided to business-expense-splurge for the in-flight wifi, which is about as fast as a snail in the process of peacefully passing away. This means the only scrap of entertainment I can garner from my laptop is writing code in MATLAB. Writing fuckaround code in a pretend programming language in a rickety IDE has a provided surprising source of succor; if you were here you’d know it too because you’d notice I have been sitting FOR HOURS WITHOUT MY SEATBELT ON because I was simply too enraptured by the alternating tides of hate and happiness that MATLAB so easily exerts on the user.

Basically, I’m working on a GUI that allows a user to programmatically  create test limits for test data, while also allowing the user to efficiently adjust the limits where our absurd test data manages to invalidate centuries of statistical knowledge. This requires allowing the user to load a specific test from within an absurdly packaged data file which comes from a test system written by someone who clearly much prefers obfuscating and hiding things over effective data collection WHICH in turn means deeply and variably nested structures. Like 400-megabyte-CSV, stuck-in-limbo-with-Leonardio-DiCaprio, booger-that-you-can-feel-but-after-several-embarrassing-red-lights-you-cannot-remove levels deep.

Therefore, after careful perusal of mathworks, I wrote the following code. It uses recursion to return an array of strings describing each and every branch of a struct, down to the twig. It is surely my greatest accomplishment thus far.

function allfields=fieldnamesr(struct);
% FIELDNAMESR recursively explores the depths of nested structs To find all
% possible branches
%      fuck yeah recursion
fields=fieldnames(struct); %are there any field names?
idx=1; %increment variable
for i=1:1:size(fields,1) %for all field names
    if isstruct(struct.(fields{i})) %see if that field name itself is a structure 
        temp=structRecurrr(struct.(fields{i})); %if also structure, then we must go deeper!
        for j=1:1:length(temp) %for all returned values 
        allfields{idx,1}=sprintf('%s.%s',fields{i},temp{j}); %return a string containing returned values
        idx=idx+1; %increment
        end
    else
        allfields{idx}=fields{i}; %if field name not struct, then we are at bottom level
        idx=idx+1; %increment
    end
end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s