I need help clarifying this part of the code
3 views (last 30 days)
Show older comments
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
Answers (1)
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
% 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,:).'
% verify that results are identical
immse(obtained_nodes_table1.X,obtained_nodes_table.X)
immse(obtained_nodes_table1.Y,obtained_nodes_table.Y)
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.
0 Comments
See Also
Categories
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!