0
votes

I have a structure with two fields and I am passing this structure to a function in scilab. How to access elements of this structure in the called function?

%Scilab console
S=struct('day',30,'month','may');
fun(S);

%called function
function fun(element)
    fields=fieldnames(element);
    disp(element.fields(1));
    disp(element.fields(2));
endfunction;

I tried bit differently,like

disp(element.(fields(1)));
disp(element.(fields(2)));

and changed '()' to '{}' and '[]',but none of them given me the output I required

Is there any way to do this?

thanks in advance =)

1

1 Answers

0
votes

Accessing all elements without knowing number of fields or field names

Using getfield you can extract fields by name. If you iterate through all fieldnames returned by fieldnames you can get all fields. See example below.

function fun(element)
    fields=fieldnames(element);
    for i=1:length(fields(1,:))-1
        fieldname = fields(i)
        fielddata = getfield(fields(i), element)

        printf('%s: %s\n', string(fieldname), string(fielddata))
    end
endfunction;

Accessing fields if you know the field names

If you know the fieldnames of a struct you can simply call them directly.

function fun2(date_struct)
       printf('day: %s\n', string(date_struct.day))
       printf('month: %s\n', string(date_struct.month)) 
endfunction