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

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.

Related

2D Array Printing as Reference

I have the code similar to below:
my #array1 = (); #2d array to be used
my $string1 = "blank1";
my $string2 = "blank2";
my $string3 = "blank3";
my #temp = ($string1, $string2, $string3);
push (#array1, \#temp);
The reason I am assigning the strings and then putting them into an array is because they are in a loop and the values get updated in the loop (#array1 is not declared in the loop).
When I run my program, it only gives me a reference to an array rather than an actual 2D array. How can I get it to print out the content as a 2D array and not as a reference or flattened out to a 1D array?
I would like an output like [[blank1, blank2, blank3],....] so i can access it like $array1[i][j]
An array can only have scalars for elements. Thus this includes references, to arrays for example, what enables us to build complex data structures. See perldsc, Tom's Perl Data Structure Cookbook.
Elements of those ("second-level") arrays are accessed by dereferencing, so $array1[0]->[1] is the second element of the array whose reference is the first element of the top-level array (#array1). Or, for convenience, a simpler syntax is allowed as well: $array1[0][1].
If we want a list of all elements of a second-level array then dereference it with #, like:
my #l2 = #{ $array1[0] }; # or, using
my #l2 = $array1[0]->#*; # postfix dereferencing
Or, to get just a few elements of the array, but in one scoop -- a slice
my #l2_slice = #{$array1[0]}[1..2]; # or
my #l2_slice = $array1[0]->#[1..2]; # postfix reference slice
what returns the list with the second and third elements of the same second-level array.
The second lines are of a newer syntax called postfix dereferencing, stable as of v5.24. It avails us with the same logic for getting elements as when we drill for a single one, by working left-to-right all the way. So ->#* to get a list of all elements for an arrayref,->%* for a hashref (etc). See for instance a perl.com article and an Effective Perler article.
There is a thing to warn about when it comes to multidimensional structures built with references. There are two distinct ways to create them: by using references to existing, named, variables
my #a1 = 5 .. 7;
my %h1 = ( a => 1, b => 2 );
my #tla1 = (\#a1, \%h1);
or by using anonymous ones, where arrayrefs are constructed by [] and hashrefs by {}
my #tla2 = ( [ 5..7 ], { a => 1, b => 2 } );
The difference is important to keep in mind. In the first case, the references to variables that the array carries can be used to change those variables -- if we change elements of #tla1 then we really change the referred variables
$tla1[0][1] = 100; # now #a1 == 5, 100, 7
Also, changing variables with references in #tla1 is seen via the top-level array as well.
With anonymous arrays and hashes in #tla this isn't the case as elements (references) of #tla access independent data, which cannot be accessed (and changed) in any other way.
Both of these ways to build complex data structures have their uses.

How to show elements of array?

I have a small problem. I created a large array.
It looks like this:
var Array = [
["text10", "text11", ["text01", "text02"]],
["text20", "text21", ["text11", "text12"]]
]
If we write this way: Array[0] that shows all the elements.
If we write this way: Array[0][0] that shows "text1".
If we write this way: Array[0][2] that shows
-2 elements
-- 0: "text01"
-- 1: "text02"
.
If we write this way: Array[0][2].count or Array[0][2][0] it will not work
How do I choose each item, I need these elements for the tableView
The problem basically is that your inner array is illegal. Swift arrays must consist of elements of a single type. You have two types of element, String and Array Of String. Swift tries to compensate but the result is that double indexing can’t work, not least because there is no way to know whether a particular element will have a String or an Array in it.
The solution is to rearchitect completely. If your array entries all consist of the same pattern String plus String plus Array of String, then the pattern tells you what to do; that should be a custom struct, not an array at all.
as #matt already answered but I want to add this thing
Why Array[0][2].count or Array[0][2][0] not work
If you Define array
var array = [
["text10", "text11", ["text01", "text02"]],
["text20", "text21", ["text11", "text12"]]
]
And when you type array you can see it's type is [[Any]] However it contains String as well as Array
So When you try to get Array[0][2] Swift does not know that your array at position 2 has another array which can have count
EDIT
What you are asking now is Array of dictionary I suggest you to go with model i.e create struct or class and use it instead of dictionary
Now If you want to create dictionary then
var arrOfDict = ["text10" : ["text01", "text02"] , "text11" : ["text11", "text12"]]
And you can access with key name let arrayatZero = arrOfDict["text10"] as? [String]

cell array of cell array in a structure MATLAB

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)})

push ELEMENTS of array to an array using Perl

using Perl I am trying to push the elements of an array to another array, and not the whole array. But I'm not getting my goal.
I tried this:
push #tmp_entities_all, #tmp_entities;
But I got the whole small array as an element in the bigger array.
Then I tried it with a loop:
for (#tmp_entities) {push #tmp_entities_all, $_;}
But the same results, the whole #tmp_entities appears as an element, and that what I dont want.
I need one dimension in the array and not array of arrays!! Should I cast something before pushing? or what is the problem?
Thanx a lot.
Out of your comments, its obvious, that #tmp_entities contains only one element, that is an array reference to the elements that you expected to be elements of #tmp_entities.
So you perhaps declared your array with an array refence instead of using a set of elements.
The line
push #tmp_entities_all, #tmp_entities;
definitly works for a normal array.
In your case, your could try ...
push #tmp_entities_all, $tmp_entities[0];
or you simply try to initialize your array with its value like
my #tmp_entities = ( 1, 2, 3 ); # initialize array with 3 elements of type int
instead of
my #tmp_entities = [ 1, 2, 3 ]; # initialize array with 1 element that is an array reference with 3 elements of type int
I know, that this is the case, because this is why your for-loop sample works with #$_ ;D (it is equivalent to push #tmp_entities_all, $tmp_entities[0]; in this situation).

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

Resources