Use cellfun instead of for loop
1 view (last 30 days)
Show older comments
I have a matrix BIGRAMPROB of 10*10*5 cell and i am performing some operation for that i wrote a function. But the problem i am facing is that i want to replace for loop in my code with cellfun and again i want my BIGRAMPROB cell matrix as output. I Have attached a mat file which contain this BIGRAMPROB(10,10,5) cell mat
CODE
function [ BIGRAMPROB ] = Untitled( BIGRAMPROB )
probmat = BIGRAMPROB(:,:,1);
totalnoofvalidbigramunsmoothed = sum(cell2mat(BIGRAMPROB(2:end,1,4)));
for i=2:size(BIGRAMPROB,1) // i want to replace these two for loop with cellfun
for j=2:size(BIGRAMPROB,2) // i want to replace these two for loop with cellfun
BIGRAMPROB{i,j,1} = max(BIGRAMPROB{i,j,2}-.75,0)/BIGRAMPROB{i,1,3} + ((.75/BIGRAMPROB{i,1,3})*BIGRAMPROB{i,1,4})*(sum(cell2mat(probmat(2:end,j))>0)/totalnoofvalidbigramunsmoothed); // I want to perform this operation for each cell
end
end
This function is calculating the probabilty for each cell in BIGRAMPROB(:,:,1) by using all other value at the place BIGRAMPROB(:,:,2),BIGRAMPROB(:,:,3),BIGRAMPROB(:,:,4)BIGRAMPROB(:,:,5) end
2 Comments
Answers (1)
Jos (10584)
on 28 Feb 2014
The way to approach this is
- create a function that acts on the contents E of a single cell
- apply that function to each element of the cell array C using cellfun.
There are various ways to create the function. The function can be a separate code (or m-file). This is useful when it is a difficult function.
function out = Myfunction(E)
x = 1:numel(E) ;
temp = polyfit(x, E(:), 1) ; % example!
out = (E - polyval(P,x)) ;
and then call it like this
result = cellfun(MyFunction,C)
Another option is to define an inline function, in case it is not too difficult
MyFunction = @(E) E - mean(E(:)) % example!
result = cellfun(@MyFunction,C, 'un',0)
See Also
Categories
Find more on Loops and Conditional Statements 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!