How do I repeat a function on each and every column of a 241X1236 array?

I am able to do it for one column
cwt1 = cwt(All_mean(:,1), 1:64, 'sym8');
Here, All_mean is the 241X1236 array. cwt, 1:64 and 'sym8' is the function.
I have something like this
for
z= 1: size(All_mean, 2)
cwt1 = cwt(All_mean(:,1), 1:64, 'sym8');
cwt(z)=cwt(All_mean(:,z), 1:64, 'sym8');
end
The output I get is a 64X241 array. I need to store every output array with a name like 'cwt1', 'cwt2', 'cwt3'.... 'cwt1236'.
Please can anyone help me? I am very new to matlab.

 Accepted Answer

I would save them in a cell array:
cwtc = cell(size(All_mean,2),1); % Preallocate Cell Array
for k1 = 1:size(All_mean,2)
cwtc{k1} = cwt(All_mean(:,k1), 1:64, 'sym8');
end
Now, cwt of each column is in its own cell as a (64x241) double array. Column 1 is in ctwc{1}, and so for the rest.

4 Comments

Thank you so much! It worked beautifully. And thanks for the explanation too- I didn't realize that I had to pre-allocate.
As always, my pleasure! Thank you!
Preallocation allows MATLAB to put each element of an array created in a for loop in an existing segment of memory, rather than having to allocate a new segment for it, and in some situations, re-writing the entire array in contiguous segments in each iteration. Preallocation isn’t absolutely necessary (code will work without it), although with it, code is significantly faster and more efficient.
I see. This is very valuable information for a new programmer like me. Thanks again!

Sign in to comment.

More Answers (1)

Why would you want to do that? Managing values in form of matrices is much easier, efficient and robust as compared to naming your variables like 'cwt1', 'cwt2', ... . cwt1 is same as cwt(:,1), so use the better option. Naming the variables like that is unrecommended: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. As you mentioned, you are new to MATLAB, this is good chance for you to start following recommended coding practices to make your code efficient and less buggy.

Asked:

Dee
on 18 May 2018

Commented:

on 18 May 2018

Community Treasure Hunt

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

Start Hunting!