1

I have a cellarray whose values are used to initialize corresponding structs.

cellarr = {'NI' ; 'EQ' ; 'TA' } ;
defstr = struct('Raw', '-1')    ;

for i = 1:size(cellarr,1)
    eval([cellarr{i,1} '= defstr;'])  %Yes,I know eval is bad!Any other approach?
end

New values are then filled into the Raw field.

dataCell = [] ;
for i=1:size(cellarr,1)
    rawCell = [cellarr{i} '.Raw'] ;
    dataCell = strcat(dataCell, ', ', rawCell) ;
end
dataCell(1) = [] ;

DESIRED STATEMENT NOW  --> [NI.Raw,Eq.Raw,TA.Raw] = filldata()

function[a1,a2,a3] =  filldata(), a1 = 1 ; a2 = 2 ; a3 = 3 ; end

I am not able to execute the desired statement, even by using eval. Shall appreciate your help. filldata output count would match that of LHS of desired statement. Thanks.

Maddy
  • 2,520
  • 14
  • 44
  • 64
  • Are you familiar with [dynamic structure references](http://blogs.mathworks.com/loren/2005/12/13/use-dynamic-field-references/)? Often their judicious use resolves need for `eval` - and they're quite fast. – reve_etrange Aug 30 '11 at 04:25

1 Answers1

0

Here is a possible solution for EVAL:

%# build and eval the string: [NI.Raw,Eq.Raw,TA.Raw] = filldata()
str = sprintf('%s.Raw,',cellarr{:});
str = sprintf('[%s] = filldata()', str(1:end-1));
eval(str);

As in any other interpreted language, the use of EVAL is not best practice (but you seem to already know that). Unless you specifically need to have variables whose names can only be determined at runtime, I would use cell-arrays or array of structures instead (depending on your needs):

N = 3;
result = cell(N,1);
[result{:}] = filldata();

%# now you can access the data as:
result{1}
result{2}
%#...
Amro
  • 123,847
  • 25
  • 243
  • 454