Fast way of performing function on multiple columns of data?
Show older comments
Hi,
I have multiple columns of data on which I need to perform the same function in Matlab. The function is exactly the same, all that changes is the data on which the function is performed on.
I have around 500 columns. Is there any shortcut which will automatically give me the value from the function instead of me having to select each column and performing the function separately.
Thank you!
2 Comments
James Tursa
on 18 Mar 2015
Is the output of the function a column the same size as the input column?
Adam
on 18 Mar 2015
Have you benchmarked how long it takes to just run a for loop over all the columns? There are plenty of flashy looking ways people attempt just because they have heard for loops are bad in Matlab, but quite a few of them are slower than raw for loops even though they look fancier. You should at least know how long the simple for loop approach takes in order to compare alternative methods.
Answers (3)
A simple way is to split your matrix in a cell array of columns using num2cell and use cellfun on this cell array:
M = rand(500);
cellfun(@somefunction, num2cell(M, 1)) %apply myfun to every column of M
The exact syntax of cellfun depends on what arguments you have to pass to your function and what return values you get.
1 Comment
Thanks for the responses :) My function is essentially this link below. http://www.mathworks.com/matlabcentral/fileexchange/26546-approximate-entropy.Do you think your advice can be applied to this? Im beginning to fear ill have to spend hours doing each one individually.
Of course, you don't need to:
M = rand(500); %for example
window_length = 5; %for example
similarity_measure = 0.5; %for example
entropy_by_column = cellfun(@(col) approx_entropy(window_length, similarity_measure, col), num2cell(M, 1))
Image Analyst
on 18 Mar 2015
Just extract a column and call that function. Put into a loop to process all your columns.
[rows, columns] = size(yourData);
for col = 1 : columns
thisColumn = yourData(:, col);
columnEntropy(col) = approx_entropy(5, 0.5, thisColumn);
end
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!