waspinator
waspinator

Reputation: 6826

build and use hash table using containers.Map

I'm trying to create an expanding lookup table. I think the cell array is what I want but I'm not sure. The structure would be initialized with rows, and an unknown amount of columns. I want to be able to append to the end of each row, and access all values from a specific row.

desired structure:

[1]  [4,5] [6,7]
[2]  [4,5] [6,7] [3,6]
...
[n]  [R1,B2] [R2,B2] ... [Rm, Bm]

this is what I have so far

%%% Build the R-table

n = 360;
k = {};
v = {};
for i = 1:n
  k{end+1} = i; % how would I get n keys without this loop?
  v{end+1} = {}; % how would I get n values without this loop?
end
rTable = containers.Map(k, v);

%%% add R,B pair to key I
I = 1;
R_add = 4;
B_add = 5;
current_list_temp = rTable(I); % can I add without using a temp variable?
current_list_temp{end+1} = {[R_add, B_add]};
rTable(I) = current_list_temp;

%%% read values for Nth pair in the Ith key
I = 1;
N = 1;
temp = rTable(I); % can I read the values without using a temp variable?
R_read = temp{N}{1}(1);
B_read = temp{N}{1}(2);

Is there a better way of doing this?

Upvotes: 0

Views: 393

Answers (1)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

When used for indexing end translates to the largest allowed index and you can manipulate it by adding or multiplying it, so instead of

first_empty_cell = ?
cell{index, first_free_cell} = [4,5]

try

cell{index, end+1} = [4,5]

Upvotes: 1

Related Questions