Save several results from recursive function

5 Ansichten (letzte 30 Tage)
BYQQY
BYQQY am 29 Apr. 2021
Kommentiert: BYQQY am 1 Mai 2021
I have written some code that that takes a textfile and applies the huffman algorithm and constructs a "Huffman tree" using nested cell arrays.
Basically I have my cell array G which of size 1x2, in turn containing 1x2 cell arrays and so on until it reach the end element which is of class char.
For example G{1}{1}{1}{1}{1}{1} = 'h' which tells me that the codeword for h is 00000 (G{1} is the root).
Now I want to parse my cell array G so I can process the data easier. Basically I want to put my data in another cell array or table like
x y
char1 codeword1
char2 codeword 2
and so on...
For this I have a recursive function
function y = parsecell(c,s)
if nargin==1
s = inputname(1);
end
for i=1:numel(c)
if iscell(c{i}) && ~isempty(c{i})
parsecell(c{i},[s subs(i,size(c))])
else
disp([s(3:end) subs(i,size(c)) ' = ' c{i}])
end
end
end
which gives me outputs like
0 0 0 0 0 = h.
for every end element in G.
I'm struggling with somehow creating my new cell array or table. For example I was thinking that I could replace disp() with something like
y{end+1,1} = [s(3:end) subs(i,size(c)) ' = ' c{i}];
but I can't get it to work.
Any help is appreciated!
  2 Kommentare
Walter Roberson
Walter Roberson am 30 Apr. 2021
You are passing the numeric value of i as the first parameter of subs() but the first parameter must be a symbolic function or symbolic expression, unless you have a sufficiently old version of MATLAB in which case a character vector was also a possibility.
BYQQY
BYQQY am 1 Mai 2021
I'm not really sure what you mean here. But I'm not having any problem with (I think?) with subs().
For example if I try
x={};
parsecell(G,x)
function parsecell(c,x,s)
if nargin==2
s = inputname(1);
end
for i=1:numel(c)
if iscell(c{i}) && ~isempty(c{i})
parsecell(c{i}, x,[s subs(i,size(c))])
else
x{end+1,1} = [s(3:end) subs(i,size(c))];
x{end,2} = c{i};
end
end
end
it sort of works. But sometimes when
parsecell(c{i}, x,[s subs(i,size(c))])
is called x resets to an empty cell array and I don't know why

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 1 Mai 2021
In my experience by far the easiest way to achieve this is to use a nested function, something like (pseudocode):
function out = mymain(s);
out = {};
mynest(s)
function mynest(t)
if whatever checks you want
out{end+1} = whatever
mynest(t(2:end)) % recursive call
end
end
end
Adapt the conditions, recursion, etc. to suit your needs.
  1 Kommentar
BYQQY
BYQQY am 1 Mai 2021
Thank you! Making a nested function solved it for me.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by