I need help clarifying this part of the code

3 views (last 30 days)
Ali ibrahim
Ali ibrahim on 22 Dec 2021
Answered: DGM on 23 Dec 2021
obtained_nodes_table = nodes_table;
counter = 1;
for row = 1:numel(nodes_table.Node(:))
if nodes_table.X(row) == 1
obtained_nodes_table.X(row) = counter;
counter = counter + 1;
else
obtained_nodes_table.X(row) = 0;
end
if nodes_table.Y(row) == 1
obtained_nodes_table.Y(row) = counter;
counter = counter + 1;
else
obtained_nodes_table.Y(row) = 0;
end
end
  1 Comment
DGM
DGM on 23 Dec 2021
What are the possible values of X and Y?
What is the shape of X and Y?

Sign in to comment.

Answers (1)

DGM
DGM on 23 Dec 2021
I'm going to assume that the intent is to simplify the operations and that X and Y are numeric column vectors whose values may not necessarily be either 0 or 1.
% test struct
nodes_table.Node = (1:10)';
nodes_table.X = randi([0 3],10,1);
nodes_table.Y = randi([0 3],10,1);
% existing routine
obtained_nodes_table1 = nodes_table;
counter = 1;
for row = 1:numel(nodes_table.Node(:))
if nodes_table.X(row) == 1
obtained_nodes_table1.X(row) = counter;
counter = counter + 1;
else
obtained_nodes_table1.X(row) = 0;
end
if nodes_table.Y(row) == 1
obtained_nodes_table1.Y(row) = counter;
counter = counter + 1;
else
obtained_nodes_table1.Y(row) = 0;
end
end
obtained_nodes_table1
obtained_nodes_table1 = struct with fields:
Node: [10×1 double] X: [10×1 double] Y: [10×1 double]
% alternative routine
% assuming X,Y are numeric column vectors
xy = double([nodes_table.X nodes_table.Y].' == 1);
xy(logical(xy)) = 1:nnz(xy);
obtained_nodes_table = nodes_table;
obtained_nodes_table.X = xy(1,:).';
obtained_nodes_table.Y = xy(2,:).'
obtained_nodes_table = struct with fields:
Node: [10×1 double] X: [10×1 double] Y: [10×1 double]
% verify that results are identical
immse(obtained_nodes_table1.X,obtained_nodes_table.X)
ans = 0
immse(obtained_nodes_table1.Y,obtained_nodes_table.Y)
ans = 0
If X and Y are logical vectors, the code simplifies further. If X and Y are arbitrarily-sized arrays, then a different approach is needed.

Tags

Community Treasure Hunt

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

Start Hunting!