Use cellfun instead of for loop
조회 수: 4 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Jos (10584)
2014년 2월 28일
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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!