1

i have written a function in matlab, which is to calculate a cost function for an array:

  function [F1val, Com]=F1(Community,NeighMat)  
        global FlattedAdjMat;
        Com=zeros(numel(Community),3);
        Com(:,1)=Community';  % The First row of Com= Community's Nodes  
        % Calculating INTERNAL Edges of Community  
            for j=1:numel(Com(:,1))
                Com(j,2)=sum(FlattedAdjMat((Community),Com(j,1)));% Internal Degrees of Node j            
            end
        F1val=(nansum(Com(:,3)./((Com(:,2)+Com(:,3)))));
  end

But i have 2 problem with the line Com(j,2)=sum(FlattedAdjMat((Community),Com(j,1))),

  1. when i try to execute it in parallel using parfor:

    parfor iii=1:5
        [z,p]=F1(Community,NeighMat)
    end
    

    this error occurs in the line: Index exceeds matrix dimensions while in normal case(not Parallel) there is no problem

  2. it is very time consuming and slow down the speed.

NeighMat is a weighted adjacency matrix, Community is an array of the matrix indexes, FlattedAdjMat is adjacency matrix.

whould you please help me?

sample data:

for ii=1:10
   NeighMat{ii}=randi(10,1,10)
end

Community=[1,5,6,8,9];`

global FlattedAdjMat
FlattedAdjMat=randi([0,1],10,10)
m7913d
  • 10,244
  • 7
  • 28
  • 56
Reza Sh
  • 77
  • 7

1 Answers1

1

You have a problem with global variable. This problem is well discussed here.

I rewrite Your code a bit and it works for me perfect (Matlab 2017b Win64)

close all
clear all
clc
%% SAMPLE DATA
for ii=1:10
    NeighMat{ii}=randi(10,1,10);
end
Community=[1,5,6,8,9];
FlattedAdjMat=randi([0,1],10,10);
%% BODY
parfor iii=1:5
    [z,p]=F1(Community,NeighMat,FlattedAdjMat)
end

%% FUNCTION
function [F1val, Com]=F1(Community,NeighMat,FlattedAdjMat)
    Com=zeros(numel(Community),3);
    Com(:,1)=Community';  % The First row of Com= Community's Nodes
    % Calculating INTERNAL Edges of Community
    for j=1:numel(Com(:,1))
        Com(j,2)=sum(FlattedAdjMat((Community),Com(j,1)));% Internal Degrees of Node j
    end
    F1val=(nansum(Com(:,3)./((Com(:,2)+Com(:,3)))));
end
zlon
  • 812
  • 8
  • 24
  • 1
    It is not a duplicate. In another SO post discussed problem how to deal with global variables in parfor. Here the person had no ideas why code did not work. The answer is don't use global variable, or if you need it see link. – zlon Nov 26 '17 at 16:42