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

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

Related

Multiple Knapsacks with Fungible Items

I am using cp_model to solve a problem very similar to the multiple-knapsack problem (https://developers.google.com/optimization/bin/multiple_knapsack). Just like in the example code, I use some boolean variables to encode membership:
# Variables
# x[i, j] = 1 if item i is packed in bin j.
x = {}
for i in data['items']:
for j in data['bins']:
x[(i, j)] = solver.IntVar(0, 1, 'x_%i_%i' % (i, j))
What is specific to my problem is that there are a large number of fungible items. There may be 5 items of type 1 and 10 items of type 2. Any item is exchangeable with items of the same type. Using the boolean variables to encode the problem implicitly assumes that the order of the assignment for the same type of items matter. But in fact, the order does not matter and only takes up unnecessary computation time.
I am wondering if there is any way to design the model so that it accurately expresses that we are allocating from fungible pools of items to save computation.
Instead of creating 5 Boolean variables for 5 items of type 'i' in bin 'b', just create an integer variable 'count' from 0 to 5 of items 'i' in bin 'b'. Then sum over b (count[i][b]) == #item b

How can a non-instantiated object be accessed via dot notation? (Swift Playground)

I'm confused about the coordinate.column and coordinate.row used in the code swift plyground provided below. How was column and row accssed when I didn't instantiate the instance coordinate? If the for loop insatntiate coordinate, how was it instantiated when allcoordinates or world.allPossibleCoordinates are not a type? (There are no parathenthesis around world.allPossibleCoordinates...)
let allCoordinates = world.allPossibleCoordinates
var blockSet: [Coordinate] = []
//#-editable-code Tap to enter code
for coordinate in allCoordinates {
// Check for coordinates with a column > 5 OR a row < 4.
if coordinate.column > 2 && coordinate.row < 5 {
// Append coordinate to blockSet.
}
}
In Swift, the for in loop works a bit differently than a for loop in other languages. A for in loop strides over a range (I'm assuming allCoordinates is strideable). In the provided example, if the variable allCoordinates is a strideable range, the loop will go through every single item in that range assigning each value to coordinate per iteration. For more information, have a look at Apple's Documentation

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]);

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)

Initializing structure in 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.