In Matlab, I am using a custom function with varargin as input, that acts on global variables that are cell arrays filled with structure arrays. I obtain following error message:

Cell contents reference from a non-cell array object.

In the first place, I would like to ask if anyone encountered this problem in the same setting as I did. And apart from the context, what is the meaning of this error message?


I have difficulties in reducing this problem to a MWE. The basic idea is the following. A 3x3 cell-array myArray is constructed. In the same .m file, it is possible to access its content at position {1,3} by using myArray{1,3}. Now I want to remove the reading function from main.m and define a custom function that takes the position as input and displays the content of myArray at that position.

%main.m
global myArray
%define myArray
...
%display content
myContent(i,j)

with

function [] = myContent(indexI,indexJ)
    global myArray
    disp(myArray{indexI,indexJ})
end

This results in the mentioned error message

Cell contents reference from a non-cell array object.
Error in myContent (line .)
myArray{indexI,indexJ}
1

There are 1 answers

1
Matt On

I think you are trying to address the structure-arrays with curly braces {} instead of the normal ones (). This will give you exactly the stated error-message.

Edit: Avoid using i and j as variable names since they are used for the imaginary unit. See this post for details. My example already uses a and b instead.

Try the following code for a demo on how to address the types you mentioned:

function test_cellarray
    global myArray

    % create structure array with 2 field and 2 entries
    structArr(1).field1 = 'entry1 field1';
    structArr(1).field2 = 'entry1 field2';
    structArr(2).field1 = 'entry2 field1';
    structArr(2).field2 = 'entry2 field2';

    % create cell array and write structArr to cell array
    myArray = cell(3,3);
    myArray{1,1} = structArr;

    a = 1;
    b = 1;
    s = 1;
    f = 'field1';
    myCellContent(a,b);
    myStructContent(a,b,s);
    myFieldContent(a,b,s,f);
end

function [] = myCellContent(indexA,indexB)
    global myArray
    disp('Cell content:');
    disp(myArray{indexA,indexB});
end

function [] = myStructContent(indexA,indexB,indexS)
    global myArray
    disp('Struct content:');
    disp(myArray{indexA,indexB}(indexS));
end

function [] = myFieldContent(indexA,indexB,indexS,field)
    global myArray
    disp('Field content:');
    disp(myArray{indexA,indexB}(indexS).(field));
end