How to utilize arrays in corona? - arrays

I have created this text array and image array.
How do i make it such that when a random image appears the corresponding text appears?
Example: When the image shows 9, I want the text displayed to be 9
I really need help.

Are you looking for getting the index of arrays in Lua? I'll just provide a small example.
You can create an array like:
local myArray = {"element_1","element_2",...,"element_n"}
And you can get an array element as:
print(myArray[1]) -- Prints 'element_1' (1st element)
print(myArray[n]) -- Prints 'element_n' (nth element)
So, if you have two arrays as below;
local myQuestionArray = {"1","2",...,"n"}
local myImageArray = {"img_1","img_2",...,"img_n"}
you can take the question and image with respect to a number as:
-- for number = 1
print(myQuestionArray[1]); // 1
print(myQuestionArray[1]); // img_1
-- for number = n
print(myQuestionArray[n]); // n
print(myQuestionArray[n]); // img_n
For mode details, refer: Understanding Lua tables in Corona SDK
Keep Coding.......... :)

Related

Extract Data From NetCDF4 File Using List

I am using a list of integers corresponding to an x,y index of a gridded NetCDF array to extract specific values, the initial code was derived from here. My NetCDF file has a single dimension at a single timestep, which is named TMAX2M. My code written to execute this is as follows (please note that I have not shown the call of netCDF4 at the top of the script):
# grid point lists
lat = [914]
lon = [2141]
# Open netCDF File
fh = Dataset('/pathtofile/temperaturedataset.nc', mode='r')
# Variable Extraction
point_list = zip(lat,lon)
dataset_list = []
for i, j in point_list:
dataset_list.append(fh.variables['TMAX2M'][i,j])
print(dataset_list)
The code executes, and the result is as follows:
masked_array(data=73,mask=False,fill_value=999999,dtype=int16]
The data value here is correct, however I would like the output to only contain the integer contained in "data". The goal is to pass a number of x,y points as seen in the example linked above and join them into a single list.
Any suggestions on what to add to the code to make this achievable would be great.
The solution to calling the particular value from the x,y list on single step within the dataset can be done as follows:
dataset_list = []
for i, j in point_list:
dataset_list.append(fh.variables['TMAX2M'][:][i,j])
The previous linked example contained [0,16] for the indexed variables, [:] can be used in this case.
I suggest converting to NumPy array like this:
for i, j in point_list:
dataset_list.append(np.array(fh.variables['TMAX2M'][i,j]))

Apply a string value to several positions of a cell array

I am trying to create a string array which will be fed with string values read from a text file this way:
labels = textread(file_name, '%s');
Basically, for each string in each line of the text file file_name I want to put this string in 10 positions of a final string array, which will be later saved in another text file.
What I do in my code is, for each string in file_name I put this string in 10 positions of a temporary cell array and then concatenate this array with a final array this way:
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector{1:10}=labels{i};
final_vector=horzcat(final_vector,temp_vector);
end
But when I run the code the following error appears:
The right hand side of this assignment has too few values to satisfy the left hand side.
Error in my_example_code (line 16)
temp_vector{1:10}=labels{i};
I am too rookie in cell strings in matlab and I don't really know what is happening. Do you know what is happening or even have a better solution to my problem?
Use deal and put the left hand side in square brackets:
labels{1} = 'Hello World!'
temp_vector = cell(10,1)
[temp_vector{1:10}] = deal(labels{1});
This works because deal can distribute one value to multiple outputs [a,b,c,...]. temp_vector{1:10} alone creates a comma-separated list and putting them into [] creates the output array [temp_vector{1}, temp_vector{2}, ...] which can then be populated by deal.
It is happening because you want to distribute one value to 10 cells - but Matlab is expecting that you like to assign 10 values to 10 cells. So an alternative approach, maybe more logic, but slower, would be:
n = 10;
temp_vector(1:n) = repmat(labels(1),n,1);
I also found another solution
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector(:,1:10)=cellstr(labels{i});
final_vector=horzcat(final_vector,temp_vector);
end

MATLAB cell array indexing and looping

I'm trying to create a script that reads data from a text file, and plots the data onto a scatter plot.
For example, say the file name is prices.txt and contains:
Pens 2 4
Pencils 1.5 3
Rulers 3 3.5
Sharpeners 1 3
Highlighters 3 4
Where columns 2 and 3 are prices of the items for two different stores.
What my script should do is read the prices, calculates (using another function) future prices of the stores and plots these prices onto a scatter plot where x is one store and y is another. This is a silly example I know but it fits the description.
Don't worry to much about the other function that does the calculation, just assume it does what its supposed to.
Basically, I've come up with the following:
pricesfile = fopen('Prices.txt');
prices = textscan(pricesfile, '%s %d d');
fclose(pricesfile);
count = 1;
while count <= length(prices{1})
for item = constants{1}
name = constants{1}{count};
store_A = prices{2}{count};
store_B = prices{3}{count};
(...other function goes here...)
end
end
After doing this I'm completely stuck. My thought process behind this was to go through each item name, and create a vector that's assigned to this name with its two corresponding prices as items in the vector eg:
pens = [2 4]
pencils = [1.5 3]
etc. Then, I would somehow plot those items in the vector on a scatter plot and use the name of the vector as a label.
I'm not too sure how to carry out the rest of my code or even if what I've written will get me to the solution.
Please help and thanks in advance.
pricesfile = fopen('Prices.txt');
data = textscan(pricesfile, '%s %d d');
fclose(pricesfile);
You were on the right track but after this (through a bit of hackery) you don't actually need a loop:
plot(repmat(data{2},1,2)', repmat(data{3},1,2)', '.')
legend(data{1})
What you DO NOT want to do is create variables named after strings. Rather store them in an array with an array of the names (which is basically what your textscan code gives you). Matlab is very good at handling matrices/arrays.
You could also split your price array up for example:
names = prices{1};
prices = [data{2:3}];
now you can perform calculations on prices quite easily like
prices_cents = prices*100;
plot(prices_cents(:,[1,1]), prices_cents(:,[2,2]))
legend(names)
Note that the [1,1] etc above is just using indexing as a short hand to achieve what repmat does...

AS3 Array pulling specific information

I am using an array to keep information about 2 blocks that have landed. I then need to pull the spriteoffset from this array. How do I do this? My method below does not work.
aryBlockRow[(elementbody.yp + elementbody.block[ii].yp)/BLOCKSIZE][(elementbody.xp + elementbody.block[ii].xp)/BLOCKSIZE] = new ElementBlock((elementbody.xp + elementbody.block[ii].xp), (elementbody.yp + elementbody.block[ii].yp), elementbody.block[ii].spriteoffset);
trace("Block row: "+aryBlockRow.block[ii].spriteoffset)
Alternatively, each block has a tag (block[ii].tag), is it possible to pull this information from aryBlockRow, or is it not as I'm not specifically adding it?
Thanks
--
To clarify:
I am creating a tetris style game, however there are 4 different elements. In order to destroy the elements, I need to know when 4 of the same are in a line. The way I am planning to do this is having each of the elements having a variable ("tag") of either 0,1,2 or 3. I am calling the variable elementbody, and within it has an array "block".
trace("Left tag is: "+elementbody.block[0].tag)
trace("Right tag is: "+elementbody.block[1].tag)
This returns:
Left tag is: 3
Right tag is: 1
Which is correct.
What I now need to do is be able to continue to trace the tags once the elements have landed. As such, I am placing them into a new Array:
for(ii = 0; ii < elementbody.block.length; ii++) {
aryBlockRow[(elementbody.yp + elementbody.block[ii].yp)/BLOCKSIZE][(elementbody.xp + elementbody.block[ii].xp)/BLOCKSIZE] = new ElementBlock((elementbody.xp + elementbody.block[ii].xp), (elementbody.yp + elementbody.block[ii].yp),
elementbody.block[ii].spriteoffset);
Spriteoffset for each of the blocks (block[0], block[1]) will return either 0, 30, 60 or 90. If I can get this returned, then I can work out whether it has 4 in a row.
What I need to know is: Is it possible to pull "spriteoffset" from the aryBlockRow array, or do I need to somehow store this information elsewhere?
Elementbody changes to the new element everytime it lands on the bottom, and the existing is saved in this array, which is why I can not use my current method.

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