Initializing structure in Matlab - matlab

I am trying to initialize a structure in MATLAB similar to how C code does
typedef struct{
float x;
float y;
} Data
Data datapts[100];
From matlab, I know this is how to create a structure:
Data = structure('x',0,'y',0)
but how do you create 100 instances of it?
Or is this not usually done in MATLAB? Does MATLAB prefer dynamic allocation whenever there is new data to add?
Thanks for all your help..

I don't know C, so I don't know how your code initializes the structure. However, consider these two possibilities:
1. A struct array data with 100 elements, each of which has two fields x and y
You can initialize an empty struct with
data = struct('x', cell(100,1), 'y', cell(100,1));
and you access each element of the struct array as data(1) and each of these is a struct. Typically, these are used when you have several equivalent "things" with the same set of properties, but different values for each.
Example:
elements = struct(...
'name', {'Hydrogen', 'Helium', 'Lithium'},...
'atomicWeight', {1, 4, 7}, ...
'symbol', {'H', 'He', 'Li'});
elements(1)
ans =
name: 'Hydrogen'
atomicWeight: 1
symbol: 'H'
So you can access each individual struct to get to its properties. Now if you wanted to append a struct array with the next 10 elements to this list, you can use cat, just like you would for matrices.
2. A struct data with two fields x and y, each with 100 elements
You can initialize this as
data = struct('x',zeros(100,1),'y',zeros(100,1));
and you access each element of the field as data.x(1). This is typically used when you have one "thing" with several properties that can possibly hold different values.
Example:
weather=struct('time',{{'6:00','12:00','18:00','24:00'}},...
'temperature',[23,28,25,21]);
Once you understand structs and struct arrays and how they're used and indexed, you can use them in more complicated ways than in the simple illustration above.

repmat(Data,100,1);
You can assign data to it with:
Data(1).x = 10;
Data(1).y = 20;

In addition to the other methods described by #yoda and #Jacob, you can use cell2struct.

Related

How do I find the first struct where a particular member has a specific value?

Background
I have a data vector, called STRUCT_A that contains the following structs. Each of these structs have sub values that are populated from a Jenkins build at random. Below is an example of one instance of this data vector:
BEGIN STRUCT for STRUCT_A
somemember_: 4
anothermember_: 3
location_: "New York"
END STRUCT for STRUCT _A
BEGIN STRUCT for STRUCT_A
somemember_: 6
anothermember_: 123
location_: "South Bend"
END STRUCT for STRUCT_A
BEGIN STRUCT for STRUCT_A
somemember_: 10
anothermember_: 6
location_: "Baton Rouge"
END STRUCT for STRUCT_A
You can access any particular member with the following syntax: STRUCT_A.anothermember(2) will return 123 for example.
Problem and attempted solution
I want to find the very first struct where a 1 occurs in the anothermember_: member, then return the value of somemember_ in that very same struct. I have done some research on the find command, but this focuses on members of one vector. My situation deals with structs that have multiple members. Below is the closest example of what I am trying to do:
The picture above shows a 4-by-4 magic square matrix called X. What I am trying to do in the example above is find the first 2 in the matrix, which in this case is located at position five. Where this 2 is located will change each time the Jenkins build is run. The example above deals with the first half of my broader issue. However, I am not sure how to translate this method into a struct, hence my question...
Question
How do I find the first struct where a a particular member of said struct has a specific value?
A possible solution:
% Reproduction example
a = struct('somemember_',1);
b = struct('somemember_',2);
c = struct('somemember_',2);
struct_array = [a b c];
elementOfInterest = 2;
% Find index of first occurence of element of interest in the struct array
find([struct_array.somemember_] == elementOfInterest,1)
returns
2

I'm having trouble shuffling a deck of cards in Matlab. Need help to see where I went wrong

I currently have the deck of cards coded, but it is unshuffled. This is for programming the card game of War if it helps. I need to shuffle the deck, but whenever I do, it will only shuffle together the card numbers and the suits, not the full card. For example, I have A identified as an ace and the suits come after each number. A normal card would be "AH" (an ace of hearts) or "6D" (a six of diamonds). Instead, it will output "5A" as one of the cards, as in a 5 of aces. I don't know how to fix this, but the code that I currently have is this:
card_nums = ('A23456789TJQK')';
card_suits = ('HDSC')';
unshuffled_deck = [repmat(card_nums,4,1),repmat(card_suits,13,1)];
disp(unshuffled_deck)
shuffled_deck = unshuffled_deck(randperm(numel(unshuffled_deck)));
disp(shuffled_deck)
I would appreciate any help with this, and thank you very much for your time!
You're creating a random permutation of all of the elements from both columns of unshuffled_deck combined. Instead you need to create a random permutation of the rows of unshuffled_deck:
shuffled_deck = unshuffled_deck(randperm(size(unshuffled_deck,1)),:);
The call to size gives you the number of rows in the deck array, then we get a random permutation of the row indices, and copy the row (value, suit) as a single entity.
Here's a version using a structure array in response to #Carl Witthoft's comment. I was afraid it would add too much complexity to the solution, but it really isn't bad:
card_nums = ('A23456789TJQK')';
card_suits = ('HDSC')';
deck_nums = repmat(card_nums,4,1);
deck_suits = repmat(card_suits,13,1);
cell_nums = cellstr(deck_nums).'; %// Change strings to cell arrays...
cell_suits = cellstr(deck_suits).'; %// so we can use them in struct
%// Construct a struct array with fields 'value' and 'suit'
unshuffled_deck = struct('value',cell_nums,'suit',cell_suits);
disp('unshuffled deck:');
disp([unshuffled_deck.value;unshuffled_deck.suit]);
%// Shuffle the deck using the number of elements in the structure array
shuffled_deck = unshuffled_deck(randperm(numel(unshuffled_deck)));
disp('shuffled deck:');
disp([shuffled_deck.value; shuffled_deck.suit]);
Here's a test run:
unshuffled deck:
A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK
HDSCHDSCHDSCHDSCHDSCHDSCHDSCHDSCHDSCHDSCHDSCHDSCHDSC
shuffled deck:
4976TT93KTJQJATK953A75QA82Q6226K5J784J4A3372486K859Q
CHSSSHCDSCSSHDDCDSHHCDHSDDCDHCCHHCHHHDDCSCDSSCHDSCSD
To access an individual card, you can do:
>> shuffled_deck(2)
ans =
scalar structure containing the fields:
value = 9
suit = H
Or you can access the individual fields:
>> shuffled_deck(2).value
ans = 9
>> shuffled_deck(2).suit
ans = H
Unfortunately, I don't know of any way to simply index the struct array and get, for instance, 9H as you would in a regular array using disp(shuffled_deck(2,:)). In this case, the only option I know of is to explicitly concatenate each field:
disp([shuffled_deck(2).value,shuffled_deck(2).suit]);

Remove data from struct bigger than a certain value

I have a struct, that's a <1x1 struct>, and I'm trying to edit a field in the struct based on the values. The field is called GeoDist_Actual and the struct is called GeoDist_str. The field GeoDist_Actual is a <262792x1 double>, and this is the code I was trying to use in order to get rid of the values that are greater than 1.609344e+05.
i =1;
for i=i:size(GeoDist_str.GeoDist_Actual)
if GeoDist_str.GeoDist_Actual(i,1 > 1.609344e+05
GeoDist_str.GeoDist_Acutal(i,1) = [];
end
end
How would I append or alter this code in order to make it function like I'm aiming? I considered setting all the values to 0, but I'm going to have to go backwards from this in order to get back GPS values, doing a reverse-Vincenty(spherical) calculation, and I'd like to just completely get rid of the values that don't comply with the if condition.
If I can narrow down the question at all, let me know, and thank you for your help in advance!
Edit: I've noticed that when I changed out the section
GeoDist_str.GeoDist_Actual(i,1) = [];
for
GeoDist_str.GeoDist_Actual(i,1) = 0;
It didn't actually solve anything, instead it didn't access the field "GeoDist_Actual" within the struct "GeoDist_str", it just created a mirror field with values of 0.
Consider this example:
% a 10-by-1 vector
x = [1;2;3;4;5;6;7;8;9;10];
% remove entries where the value is less than five
x(x<5) = [];
This is called logical indexing, no need for loops.
Consider the following simple example:
A.a = 1:5;
A =
a: [1 2 3 4 5]
now delete all elements bigger 3;
A.a = A.a( ~(A.a > 3) );
A =
a: [1 2 3]
or alternatively:
A.a( A.a > 3 ) = []
For your case it's a little more bulky:
GeoDist_str.GeoDist_Actual = ...
GeoDist_str.GeoDist_Actual( ...
~(GeoDist_str.GeoDist_Actual > 1.609344e+05) )

Perform action on all fields of structure

I wonder if it's possible to perform an action on all fields of a structure at once?
My scenario:
I have data from an eye tracker device. It is stored in a struct Data, and has the following fields:
Data.positionX
Data.positionY
Data.velocity
Data.acceleration
Each field contains a vector of integers. Suppose I want to delete sample number 10 from my data stream. I would have to do the following:
Data.positionX(10) = [];
Data.positionY(10) = [];
Data.velocity(10) = [];
Data.acceleration(10) = [];
How would I do this more efficiently?
Yes, use dynamic field names.
fields = fieldnames(Data);
for i=1:length(fields)
field = fields{i};
Data.(field)(10) = [];
end
If your data is simple enough, it may be worth switching to a structure where you index the data directly instead of its contents
Data(10).positionX
Data(10).positionY
...
then it would have been as simple as
Data(10)=[]
Or alternately, if you have a bunch of vectors you want to store together, you may be better off storing them in a matrix:
M = [positionX positionY] %And so on, possibly transposed
Then it would have been as simple as:
M(10,:)=[];

Easy way to create and initialise a 3D table of structs in Matlab

I would like to be able to initialise a big table in matlab easily.
Say I have the bounds x, y, z = 5, 4, 3. I want to be able to make a 5x4x3 table where each element is a struct that stores count and sum. Count and sum in this struct should be 0 when initialised.
I thought it would be enough to do this:
table = []
table(5,4,3) = struct('sum', 0, 'count', 0)
And this would work for a double but not with a structure evidently.
Any ideas?
EDIT:
As another question, (bonus if you will) is there a way to force matlab to store the struct, but when you access the element (i.e., table(1, 2, 3)) get it to return the average (i.e., table(1,2,3).sum/table(1,2,3).count).
Its not vital to the question but it would certainly be cool.
You'll need just to replace the line table = [] to avoid the error, that is
clear table;
table(5,4,3) = struct('sum', 0, 'count', 0)
works fine. Note, however, that this command only initializes one field of your array, i.e., the memory allocation is incomplete. To initialize all fields of your array, you can use
table2(1:5,1:4,1:3) = struct('sum', 0, 'count', 0)
to visualize the difference, use whos, which returns
>> whos
Name Size Bytes Class Attributes
table 5x4x3 736 struct
table2 5x4x3 8288 struct
Your second question can be solved, for instance, by using anonymous functions
myMean = #(a) a.sum./a.count; %define the function
myMean(table2(2,2,2)) % access the mean in the field (2,2,2)