MATLAB: Codegen error: The left-hand side has been constrained to be non-complex, but the right-hand side is complex

codegencomplexdpigenreal

I am new to matlab and am trying to compile legacy matlab code into C. I come across the following error when doing so:
??? The left-hand side has been constrained to be non-complex, but the right-hand side is complex. To
correct this problem, make the right-hand side real using the function REAL, or change the initial
assignment to the left-hand side variable to be a complex value using the COMPLEX function.
The code that it complains on is in the comments of the code below:
function [z_out,ovf_flag,ovf_cnt] = fxpt_sgn_saturate(z_in,Nb_out)
Nb_out=(Nb_out<=0)+(Nb_out>0)*Nb_out;
max_val = 2^(Nb_out-1)-1;
min_val = -2^(Nb_out-1);
ovf_cnt = 0;
tmp_ind = find(real(z_in) > max_val);
z_in(tmp_ind) = max_val+1j*imag(z_in(tmp_ind)); // ERROR OCCURS HERE
ovf_cnt = ovf_cnt + numel(tmp_ind);
tmp_ind = find(real(z_in) < min_val);
z_in(tmp_ind) = min_val+1j*imag(z_in(tmp_ind));
ovf_cnt = ovf_cnt + numel(tmp_ind);
tmp_ind = find(imag(z_in) > max_val);
z_in(tmp_ind) = real(z_in(tmp_ind))+1j*max_val;
ovf_cnt = ovf_cnt + numel(tmp_ind);
tmp_ind = find(imag(z_in) < min_val);
z_in(tmp_ind) = real(z_in(tmp_ind))+1j*min_val;
ovf_cnt = ovf_cnt + numel(tmp_ind);
z_out = z_in;
ovf_flag = ~(ovf_cnt==0);
return
I don't particularly understand the code well. Any ideas how to fix this issue?
Thanks

Best Answer

Before your line
z_in(tmp_ind) = max_val+1j*imag(z_in(tmp_ind)); // ERROR OCCURS HERE
do
z_in = complex(z_in, zeros(size(z_in), class(z_in)) );
The issue is that the z_in you are passing in to the routine has been deduced as being non-complex, but you are trying to store complex values in the array.
If you are expecting that z_in should be already complex, then do not do the above change: instead you need to go up a level to where you are calling the routine, and figure out why it does not know that it is complex.