Easy way to create and initialise a 3D table of structs in Matlab - 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)

Related

Most efficient way to store dictionaries in Matlab

I have a set of IDs associated with costs which is just a double value. IDs are integers and unique. Two IDs may have same costs. I stored them as:-
a=containers.Map('KeyType','uint32','ValueType','double');
a(1)=7.3
a(2)=8.4
a(3)=7.3
Now i want to find the minimum cost.
b=[];
c=values(a);
b=[b,c{:}];
cost_min=min(b);
Now i want to find all IDs associated i.e. 1 and 3 with the minimum cost i.e. 7.3. I can collect all the keys into an array and then do a for loop over this array. Is there a better way to do this entire thing in Matlab so that for loops are not required?
sparse matrix can work as a hashmap, just do this:
a= sparse(1:3,1,[7.3 8.4 7.3])
find(a == min(nonzeros(a))
There are methods which can be used on maps for this kind of operations
http://se.mathworks.com/help/matlab/ref/containers.map-class.html
The approach finding minimum values and minimum keys can be done something like this,
a=containers.Map('KeyType','uint32','ValueType','double');
a(1)=7.3;
a(3)=8.4;
a(4)=7.3;
minval = inf;
minkeys = -1;
for k = keys(a)
val = a.values(k);
val = val{1};
if (val < minval(1))
minkeys = k;
minval = val;
elseif (val == minval(1))
minkeys = [minkeys,k];
end
end
disp(minval);
disp(minkeys);
This is not efficient though and value search is clumsy for maps. This is not what they are intended for. Maps is supposed to do efficient key lookup. In case you are going to do a lot of lookups and this is what takes time, then use a map. If you need to do a lot of value searches, I would recommend that you use a matrix (or two arrays) for this instead.
idx = [1;3;4];
val = [7.3,8.3,7.3];
minval = min(val);
minidx = idx(val==minval);
disp(minval);
disp(minidx);
There is also another post with an example where it is shown how a sparse matrix can be used as a hashmap. Let the index become the key. This will take about 3 times the memory as all non-zero elements an ordinary array, but a map uses more memory than an array as well.

How to filter and save each variable on matlab

I have a data (matrix) with 3 columns : DATA=[ID , DATE, Value]
I want to filter my data by ID for example DATAid1= DATA where ID==1 and so on ..
for that I write this code in MATLAB
load calibrage_capteur.mat
data = [ID ,DATE , Valeur]
minid = min(data(:,1));
maxid = max(data(:,1));
for i=minid:maxid
ind=find(data(:,1) == i)
dataID = [ID(ind) ,DATE(ind) , Valeur(ind)]
end
As a result he register the last value in this example the max ID=31 so he register dataId31. Now I need how to save the variable each iteration. How can I do this?
You will want to use a cell array to hold your data rather than saving them as independent variables that are named based upon the ID.
data_by_ID = cell();
ids = minid:maxid;
for k = 1:numel(ids)
data_by_ID{k} = data(data(:,1) == ids(k),:);
end
Really though, depending on what you're doing with it, you can use data all of the time since all operations are going to be faster on a numeric matrix than they are on a cell array.
%// Do stuff with data ID = 10
do_stuff(data(data(:,1) == 10, :));
Update
If you absolutely must name your variables you could do the following (but please don't do this and use one of the methods above).
for k = 1:numel(ids)
eval(['dataId', num2str(ids(k)), '= data(k,:);']);
end
Your question is a bit unclear but it sounds like you simply want to save the result at each iteration of the for loop.
I'm assuming min and max id are arbitrary and not necessarily the variable you are trying to index on.
kk = min_id:max_id;
dataID=nan(size(kk));
for ii = 1:numel(kk)
ind=find(data(:,1) == kk(ii))
dataID(kk) = [ID(ind) ,DATE(ind) , Valeur(ind)]
end
This is better than indexing by min_id or max_id since it isn't clear that min_id starts at at 1 (maybe it starts at 0, or something else.)

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

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.