I have a function that uses Module
. The function takes as input a .csv
that can have as many columns as it wishes to, and it will import all of them. The user just needs to call function[num]
, and it will import num
columns of the .csv
. This of course is a oversimplified version of the idea of my code. To accomplish the "unknown" number of variables I used MapThread
like the following.
f[num_]:=Module[{colorlist, cnamelist},
colorlist = {};
For[i = 0, i < num, i++,
AppendTo[colorlist,
Directive[Opacity[1],
Defer[RGBColor] @@@ ColorData["Rainbow", 1 - i/(num - 1)]]]];
cnamelist = {};
For[i = 1, i <= num, i++,
AppendTo[cnamelist, StringJoin["c", ToString[i]]]];
MapThread[Set, {ToExpression[cnamelist], colorlist}];];
If num
is set to 7, then it creates a list colorlist={"c1", "c2" ... "c7"}
and then defines the variables c1, c2... c7
with a corresponding color through MapThread
.
Everything works, the issue is that c1,c2, ... c7
are now defined and I cant use MapThread
again. Since its inside a function the purpose it to use it again.
I tried adding to the function in the last line the following bit
For[i = 1, i <= num, i++, Clear[cnamelist[[i]] ] ]
But it returns the error Clear::ssym: cnamelist[[i]] is not a symbol or a string.
How can I clear all the variables. I have more lists like cnamelist
in my code that needs to be cleared for it to work again, but I would assume the same procedure would work.
Clear[cnamelist]
orDelete[cnamelist , i]
, if you want to delete single elements from the list (note that the list gets shorter so that enumeration changes). $\endgroup$Clear[cnamelist]
clearscnamelist
but not the variablesc1,c2, ...c7
that are inside it. Tried puttingDelete[cnamelist , i]
instead ofClear[cnamelist[[i]] ]
in theFor
but nothing changed, they dont clear. $\endgroup$AppendTo
. Usually it involves copying the whole list. Just compare these timings:a = {}; Do[AppendTo[a, i], {i, 100000}]; // AbsoluteTiming b = Range[1000000]; // AbsoluteTiming
$\endgroup$.csv
. The bit here is the color portion of the plots which copies the structure (code wise) of the part that imports the data. I decided to import the data like this because each column has a different label (data means something different), and the user picks the order in which to show the data in a stacked plot. So it was very relevant to know and manage the labels because order is crucial. $\endgroup$