Search code examples
functionmatlabtypesstructure

Problem with data type when calling a function which modify structure Matlab


I have a problem with the data type when calling a matlab function I coded.

Here is my problem :

With another function I coded, I open and get the name and types of the 'inport' and 'outport' blocks of a Simulink file. I store all this in a structure.

All this works normally.

The problem comes with my second function. This one retrieves the old structure and according to the inport types, creates and completes a new field with the appropriate test sequences according to the type (double, single, uint8, logical...) of the inport concerned. But the problem is that when I check the type of the sequences obtained with my function, by calling it in a matlab script, I only get 'double'. No boolean, uint8, single etc. Despite the fact that I fill my sequences with the right types in my function.

function [slxStimStruct] = slxStim(schedTime,inportType,struct)

time = 0:schedTime:10; 

N = length(inportType); 

stim = cell(1,N); % Cell array in which we will stock test sequences

for i=1:N 

    v = zeros(1,length(time)-1);

    for j=1:length(time)-1    

        if strcmp(inportType(i),'boolean')    

            v(j) = logical(randi([0 1],1));

        elseif strcmp(inportType(i),'single') 
            
            v(j) = single(randn());

Then there are tests for all datatypes.

 end
   
    end

    stim{i} = v; 

end

struct.stim = stim; 

slxStimStruct = struct;

I know it has something to do with the fact that functions only work locally. It also seems to me that to solve this problem I should create a field in the structure containing the types that the test sequence can take. But I can't manage to do that either.

Does anyone know how to solve this problem ?


Solution

  • After

    v = zeros(1,length(time)-1);
    

    v is a double array. All elements of this array are doubles, and cannot be of another type. Each array in MATLAB holds a single type.

    When you do

    v(j) = single(randn());
    

    the single is converted to double to be stored in the double array.

    If you want a sequence of different types, make v a cell array:

    v = cell(1,length(time)-1);
    v{j} = single(randn());
    

    Note the curly braces used when indexing the cell array.

    A cell array stores matrices, each element is a separate array that has its own type. This is a much less efficient way to store values, if v is large it would be better to just store doubles in a double array.