Errors in converting to C code

2 Ansichten (letzte 30 Tage)
Maurilio Matracia
Maurilio Matracia am 18 Sep. 2022
Beantwortet: Yash am 30 Aug. 2023
Hello everyone,
I have the following code that I want to speed up by converting to C (I never did that before):
function [MD_a,mismatch_SminusA] = metaDistr_fun
tic
zero = 1e-6 ; Pi = 3.14159 ;
alpha = 3.5 ;
m = 1 ;
iterations = 3e1 ;
instants = 9e0 ;
sigma2 = 1e-11 ;
lambda0 = 1e-6 ;
Rd = 0.5e3 ;
Ra = 840 ;
Rb = 3286 ;
infty = 2e4 ;
xi = 20 ;
Chi = 0 ;
tau = 0.2 ;
X = linspace(0,1, 1) ; nX = length(X) ;
pTag = zeros(1,2) ; coord = {[0 0];[0 0]} ; ED = {0;0} ; EDmin = ED ; Hc = ED ; pr =0 ;
Ru=Rd
MD_s = zeros(1,nX) ; reliab = zeros(1,iterations) ; SINR = zeros(iterations,instants) ;
for i = 1:iterations
nD = poissrnd (Chi * lambda0 * pi * (Rd^2-0^2)) ;
thetaD = rand(nD,1) * 2*pi ;
rD = sqrt(rand(nD,1)*(Rd^2-0^2) + 0^2) ;
coord{1} = [ rD.*cos(thetaD) , rD.*sin(thetaD) ] ;
nTa = poissrnd(lambda0 * pi * (Ra^2-Rd^2));
nTb = poissrnd(lambda0 * pi * (infty^2-Rb^2)) ;
thetaT = rand(nTa+nTb,1) * 2*pi ;
rT = [sqrt(rand(nTa,1)*(Ra^2-Rd^2) + Rd^2); sqrt(rand(nTb,1)*(infty^2-Rb^2) + Rb^2)] ;
coord{2} = [ rT.*cos(thetaT) , rT.*sin(thetaT) ] ;
for B = 1:2
ED{B} = sqrt( (Ru-coord{B}(:, 1)).^2 + coord{B}(:, 2).^2 ) ;
if isempty(ED{B})
ED{B} = infty ; EDmin{B} = infty ;
else
EDmin{B} = min(ED{B}) ;
end
pTag(B) = xi * EDmin{B}^-alpha;
Hc{B} = gamrnd( m,1/m, length(ED{B}),instants ) ;
end
tag = find( pTag == max(pTag) ) ;
for t = 1:instants
pr = Hc{tag}( find(ED{tag}==EDmin{tag}),t ) *xi*EDmin{tag}^-alpha ;
PtotD = xi * sum(Hc{1}(:,t).*ED{1}.^-alpha) ;
Ptot = PtotD + xi * sum(Hc{2}(:,t).*ED{2}.^-alpha) ;
SINR(i,t) = pr/(Ptot-pr+sigma2) ;
end
reliab(i) = mean(SINR(i,:)>tau) ;
end
for x = 1 : nX
MD_s(x) = mean(reliab >= X(x)) ;
end
end
However, I am getting the following errors (screenshot attached), could anyone suggest me how to fix them?
Thanks in advance!

Antworten (1)

Yash
Yash am 30 Aug. 2023
Hi Maurilio,
I was able to reproduce the error using the code you provided. After analysing your code, I noticed that the cell array 'ED' changes its shape in each iteration (line 32).
You can confirm this by removing the semicolon at the end of line 32.
It's important to note that not all MATLAB codes can be converted into C code using the MATLAB Coder. Since C does not support variable-size arrays, the variable size of 'ED' cannot be converted from MATLAB to C.
One possible workaround is to use padding. You can add extra zeros at the end of the arrays to fix their size. Preallocate the size for the arrays by creating an array of zeros or ones and avoid changing their size within the loop.

Community Treasure Hunt

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

Start Hunting!

Translated by