need help the mean of this code

6 views (last 30 days)
pratama mahadika
pratama mahadika on 15 May 2019
Commented: Guillaume on 15 May 2019
% GENERATE CODE FOR GENERATING GRID
code_generate_grid = '[';
for i=1:length(grd.Nx)
code_generate_grid = [code_generate_grid 'inp.X{' num2str(i) '} '];
end
for i=1:length(grd.Nu)
code_generate_grid = [code_generate_grid 'inp.U{' num2str(i) '} '];
end
code_generate_grid = [code_generate_grid '] = ndgrid('];
for i=1:length(grd.Nx)
code_generate_grid = [code_generate_grid 'current_grd.X{' num2str(i) '},'];
end
for i=1:length(grd.Nu)
code_generate_grid = [code_generate_grid 'current_grd.U{' num2str(i) '},'];
end
code_generate_grid = code_generate_grid(1:end-1);
code_generate_grid = [code_generate_grid ');'];
can someone explain the meaning from the code with bold text
Any help would be appreciate thank you.....

Accepted Answer

Rik
Rik on 15 May 2019
This is horrible code. I would strongly suggest not using it.
However, it should be easy to see what is happening if you go throught this code line by line with the debugger.
What happens is that it generates a char array
code_generate_grid = '[';%intializes the array
for i=1:length(grd.Nx)
code_generate_grid = [code_generate_grid 'inp.X{' num2str(i) '} '];
%on i=1:
%code_generate_grid='[inp.X{1} '
%on i=2:
%code_generate_grid='[inp.X{1} inp.X{2} '
end
Then that penultimate line crops off the last space and the last line puts in a closing bracket.
DO NOT USE THIS FOR EVAL.
  5 Comments
Rik
Rik on 15 May 2019
@Guillaume: The thing is that those indices aren't even embedded in the variable names. They already are cell arrays. That is what is puzzling to me as well: if you already have cell arrays, why go to the trouble of writing this for eval?
The code below will replace the entire thing posted above, including the implied eval.
%assign some random values to required variables to make the code run
grd=struct;
grd.Nx=zeros(1,2);grd.Nu=zeros(1,2);
current_grd=struct;
current_grd.X={[1 2],[3 4]};current_grd.U={[5 6],[7 8]};
%this replaces that entire mess
inp.X=cell(1,numel(grd.Nx));
inp.U=cell(1,numel(grd.Nu));
[inp.X{:},inp.U{:}]=ndgrid(current_grd.X{:},current_grd.U{:});
Guillaume
Guillaume on 15 May 2019
Oh, yes you're right, it's even more pointless. Complexity for the sake of complexity. Possibly, at some point somebody said to the author that embedding indexing in variable names was bad and he converted to indexing but left the eval building code otherwise unchanged.
@pratama, so even more reason for you not bothering to try to understand that code. Instead, work on understanding Rik's replacement that does the same in a much saner, faster, and simpler way.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!