# Q：等效代码稀疏的MATLAB函数

I want to translate a Matlab code to C++. I use for this the Matlab-Coder. However this Matlab code uses the function Sparse(triplet) that is not performed by the Matlab coder. So i decided to write my own Sparse function in order to be translated by the Matlab coder :

``````function [ind,values]=test_new3_sparse(i,j,v,m,n)
if(isrow(i)==0) i=i'; end
if(isrow(j)==0) j=j'; end
if(isrow(v)==0) v=v'; end

k=1;
A=zeros(m,n); %this line makes a problem when "m lines and the n
%columns" are too big

for l=1:size(i,2)
A(i(l),j(l))=v(l);
end

ind=zeros(m,2);
values=zeros(1,m);

for i=1 : size(A,1)
for j=1:size(A,2)
if A(i,j) ~=0
ind(k,1)=i;
ind(k,2)=j;
values(k)=A(i,j); k=k+1;
end
end
end

end``````

This function I wrote works well when n and m are not important. However i have the error "out of memory" when they are too big. Any suggestions?

``````function [ind,values]=test_new3_sparse(i,j,v,m,n)
if(isrow(i)==0) i=i'; end
if(isrow(j)==0) j=j'; end
if(isrow(v)==0) v=v'; end

k=1;
A=zeros(m,n); %this line makes a problem when "m lines and the n
%columns" are too big

for l=1:size(i,2)
A(i(l),j(l))=v(l);
end

ind=zeros(m,2);
values=zeros(1,m);

for i=1 : size(A,1)
for j=1:size(A,2)
if A(i,j) ~=0
ind(k,1)=i;
ind(k,2)=j;
values(k)=A(i,j); k=k+1;
end
end
end

end``````

c++  matlab  sparse-matrix