Accessing variable in a table, depending on another variable

The output of the code is a table, containing the number and position of nodes in a maze.
Name = [];
Position = [];
number = 0;
Letter = 'N';
for j = 1 : size(is_node,2)
for i = 1 : size(is_node,1)
if is_node(i,j) == 1
number = number + 1;
Order = string(number);
name = Letter + Order;
Name = [Name;name];
position_y = i;
position_x = j;
Position = [Position;position_y,position_x];
end
end
end
node_table = table(Name,Position);
end
Output:
Name Position
_____ ________
"N1" 2 2
"N2" 4 2
"N3" 6 2
"N4" 10 2
"N5" 4 4
"N6" 6 4
"N7" 8 4
"N8" 10 4
"N9" 6 6
"N10" 8 6
"N11" 10 6
"N12" 2 8
"N13" 4 8
"N14" 6 8
"N15" 8 8
"N16" 10 8
"N17" 4 10
"N18" 6 10
"N19" 10 10
"N20" 2 12
"N21" 4 12
"N22" 6 12
"N23" 8 12
"N24" 10 12
I need to write a code that finds the number of a node without "N", depending on its position. For example: 10 6 should result in 11.
Any hint will help.
Thanks in advance.

1 commentaire

What have you tried and where did you have a specific problem?
You might find the new(ish) pattern family of functions of interest...

Connectez-vous pour commenter.

 Réponse acceptée

% Create a table:
is_node = false(12);
is_node(2,2) = true;
is_node(4,2) = true;
is_node(6,2) = true;
is_node(10,2) = true;
is_node(4,4) = true;
is_node(6,4) = true;
is_node(8,4) = true;
is_node(10,4) = true;
is_node(6,6) = true;
is_node(8,6) = true;
is_node(10,6) = true;
Name = [];
Position = [];
number = 0;
Letter = 'N';
for j = 1 : size(is_node,2)
for i = 1 : size(is_node,1)
if is_node(i,j) == 1
number = number + 1;
Order = string(number);
name = Letter + Order;
Name = [Name;name];
position_y = i;
position_x = j;
Position = [Position;position_y,position_x];
end
end
end
node_table = table(Name,Position)
node_table = 11×2 table
Name Position _____ ________ "N1" 2 2 "N2" 4 2 "N3" 6 2 "N4" 10 2 "N5" 4 4 "N6" 6 4 "N7" 8 4 "N8" 10 4 "N9" 6 6 "N10" 8 6 "N11" 10 6
% find the Name(s) where Position is position:
position = [10 6];
% one way:
idx = node_table.Position(:,1) == position(1) ...
& node_table.Position(:,2) == position(2);
node_number = node_table.Name(idx)
node_number = "N11"
% another way:
idx = ismember(node_table.Position,position,'rows');
node_number = node_table.Name(idx)
node_number = "N11"

1 commentaire

node_number = "N11"
node_number = "N11"
node_number = extractAfter(node_number,1)
node_number = "11"
And, if you want it to be numeric:
node_number = str2num(node_number)
node_number = 11
By the way, I restored your question so that others who have a similar question in the future may benefit.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by