cell array of cell array in a structure MATLAB - arrays

I'm trying to have a cell array of cell array in order to store data in a structure.
Here is my example :
close all;
clear all;
clc;
register = struct('thing', [], ...
'positions', cell(1));
register.positions{1}{end+1} = {[45 36]};
register.positions{2}{end+1} = {[12 87]};
register
I got this following error message :
Cell contents reference from a non-cell array object.
Error in test (line 8) register.positions{1}{end+1} = {[45 36]};
I am definitely doing something wrong, but I have unsuccessfully tried many other things.
Thank you for your help

The cell has to be initialized first. Let's break it up: Your code
register = struct('thing', [], 'positions', cell(1));
actually creates a structure with two empty fields:
>> register
register =
thing: []
positions: []
Assigning directly using end (e.g. with register.positions{1}{end+1}=4) will fail, because end in the second level will try to determine the size of the cell at register.positions{1}, but register.positions itself is empty!
So, what do we do? We could ensure that at the first time a new element at the top level is referred to, we initialize it without referring to its content. For example, register.positions{1} = [] will do the job, and
register.positions{1}{end+1} = [45 36];
will then work. (Note: here I have not encapsulated the array in another set of curly braces, because from your comments above it seems they're not necessary.)
Now, to make this a bit more convenient, you preallocate the positions field with the number of elements ('cars' in your comment), if it is known (or a number larger than expected):
register = struct('thing', [], 'positions', {cell(1, 42)})

Related

Pulling out specific column when sometimes, the array is empty

I am trying to pull out a column from inside a cell. However, sometimes, the cell is empty.
For example, if in this line, I try to pull out the last column inside PM25_win{i}, it sometimes has an array inside of size nx28. However, sometimes, the array is zero.
for i = 1:length(years)-1
PM25 = table2array(PM25_win{i}(:,end));
end
When the array is empty, the code stops and I get the error
Subscript indices must either be real positive integers or logicals.
How can I account for both cases so that the code will simply create the PM25 variable as an empty array if PM25_win{i} is empty?
You could simply add an if-else statement in the for loop.
for i = 1:length(years)-1
if isempty(PM25_win{i}(:,end))
PM25 = [];
else
PM25 = table2array(PM25_win{i}(:,end));
end
end

how to get array of properties from array of objects in matlab

I am using an array of objects in my program, and each object has several attributes. I want to be able to extract separate arrays from this array of objects, one array for each attribute.
here is a snippet of the relevant code:
dailyDataMatrix(m,n)=dailyData('',''); %creates an mxn array of dailyData objects
for i=1:m
for j=1:n
dailyDataMatrix(i,j)=dailyData(datainput1, datainput2)%dailyData constructor, sets attributes
end
end
dailyDataMatrix.attribute
But when I try to access a certain attribute as in the code above, say of type string, I get a strange result. Instead of getting an array of strings, I get something else. When I try to print it, rather than printing an array, it prints a series of individual values
ans = 'string1'
ans = 'string2'
...
When I try to call
size(dailyDataMatrix.attribute)
className = class(dailyDataMatrix.attribute)
I get
"error using size: too many input arguments" and
"error using class: The CLASS function must be called from a class constructor."
However, when I write this as
thing=dailyDataMatrix.attribute
className = class(thing)
size(thing)
I get the response
classname = 'double' and size = 1x1.
Why is this not returning an array the same size as dailyDataMatrix? And an aside question is why the two different ways of writing the code above give different results? and how can I get the result that I want?
Thanks,
Paul
You can capture all the outputs using a cell array or using square brackets if the types are same. For regular array when all values are of same type use,
thing=[dailyDataMatrix.attribute];
If the types are different you can use
thing = cell(1,N); % N is the number of elements in dailyDataMatrix
[thing{:}] = dailyDataMatrix.attribute;

initializing a 2d array, each element is a list?

So, what I am trying to do is create a variable that holds 50 lists/arrays. Accessing an element in this variable would return one of the lists. If there are no elements at a given index, I would like it to return [].
My logic to initialize this would be something like:
spectrum_map=[];
for n=1:spectrum_blocks
spectrum_map=[spectrum_map,[]];
end
However, after doing so, I simply get an empty matrix:
spectrum_map =
[]
What I want to see is something like:
spectrum_map =
[] [] [] [] [] ....
That way, if I were to access spectrum_map(2), I would see that it is empty. However, instead I would get an error that the index exceeds matrix dimensions.
Is there some other way to do what I am trying to achieve?
You can get the effect you're looking for if you use a cell array instead of a matrix.
spectrum_map = cell( 1, 50 );
spectrum_map{50}
ans =
[]
If you need to convert back to a matrix later (to perform some math on it, for instance) you can use the cell2mat function.

Inserting data into an array sequentially

I am currently trying to figure out how to design some sort of loop to insert data into an array sequentially. I'm using Javascript in the Unity3D engine.
Basically, I want to store a bunch of coordinate locations in an array. Whenever the user clicks the screen, my script will grab the coordinate location. The problem is, I'm unsure about how to insert this into an array.
How would I check the array's index to make sure if array[0] is taken, then use array[1]? Maybe some sort of For loop or counter?
Thanks
To just add onto the end of an array, just use .push().
var myArray = [];
var coord1 = [12,59];
var coord2 = [87,23];
myArray.push(coord1);
myArray.push(coord2);
myArray, now contains two items (each which is an array of two coordinates).
Now, you wouldn't do it this way if you were just statically declaring everything as I've done here (you could just statically declare the whole array), but I just whipped up this sample to show you how push works to add an item onto the end of an array.
See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push for some reference doc on push.
In case you need to know the array's length when reading the array in the future, you can use the .length attribute.
var lengthOfArray = myArray.length;
Using the .push() method as suggested by jfriend00 is my recommendation too, but to answer your question about how to work out what the next index is you can use the array's length property. Because JavaScript arrays are zero-based The length property will return an integer one higher than the current highest index, so length will also be the index value to use if you want to add another item at the end:
anArray[anArray.length] = someValue; // add to end of array
To get the last element in the array you of course say anArray[anArray.length-1].
Note that for most purposes length will give the number of elements in the array, but I said "one higher than the current highest index" above because JavaScript arrays are quite happy for you to skip indexes:
var myArray = [];
myArray[0] = "something";
myArray[1] = "something else";
myArray[50] = "something else again";
alert(myArray.length); // gives '51'
// accessing any unused indexes will return undefined

Initialize Array to Blank custom type OCAML

ive set up a custom data type
type vector = {a:float;b:float};
and i want to Initialize an array of type vector but containing nothing, just an empty array of length x.
the following
let vecarr = Array.create !max_seq_length {a=0.0;b=0.0}
makes the array init to {a=0;b=0} , and leaving that as blank gives me errors. Is what im trying to do even possible?
You can not have an uninitialized array in OCaml. But look at it this way: you will never have a hard-to-reproduce bug in your program caused by uninitialized values.
If the values you eventually want to place in your array are not available yet, maybe you are creating the array too early? Consider using Array.init to create it at the exact moment the necessary inputs are available, without having to create it earlier and leaving it temporarily uninitialized.
The function Array.init takes in argument a function that it uses to compute the initial value of each cell.
How can you have nothing? When you retrieve an element of the newly-initialized array, you must get something, right? What do you expect to get?
If you want to be able to express the ability of a value to be either invalid or some value of some type, then you could use the option type, whose values are either None, or Some value:
let vecarr : vector option array = Array.create !max_seq_length None
match vecarr.(42) with
None -> doSomething
| Some x -> doSomethingElse
You can initialize and 'a array by using an empty array, i.e., [||]. Executing:
let a = [||];;
evaluates to:
val a : 'a array = [||]
which you can then append to. It has length 0, so you can't set anything, but for academic purposes, this can be helpful.

Resources