Use cellfun instead of for loop

1 次查看(过去 30 天)
arun
arun 2014-2-28
评论: arun 2014-2-28
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 个评论
per isakson
per isakson 2014-2-28
The attachment is lost and the code is difficult to read.
arun
arun 2014-2-28
I have attached the file......Thanks for taking a look.

请先登录,再进行评论。

回答(1 个)

Jos (10584)
Jos (10584) 2014-2-28
The way to approach this is
  1. create a function that acts on the contents E of a single cell
  2. 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)
  1 个评论
arun
arun 2014-2-28
First of all thanks for your attention. I got the point and able to implement in both way if the matrix is only 2-d.In my example i am using 3-d matrix and accessing multiple elements. In case of second example you have given how can i calculate the value that is
  • totalnoofvalidbigramunsmoothed = sum(cell2mat(BIGRAMPROB(2:end,1,4)));
  • 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);
  • In this case i am not able find the value of i and j
  • I have attached a mat file of 10*10*5 cell

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by