1 view (last 30 days)

Show older comments

I have a matrix (Nodal_Coordinates). I'm trying to loop through column 1 to find Node 1, Node 2... Node n. Then once Node_1 is found, I need it to display the respective row and only column 2 and column 3. The matrix row size can change with respect to the input, so it needs to be flexible on evaluating the matrix up to nth nodes. However, the columns will always be three. Col 1 is the node number, Col 2 is the x coordinate, Col 3 is the y coordinate. Below is the code I've been trying, but it outputs the entire row instead of just the 2nd and 3rd values of the row, and it's not flexible for nth rows... it only works for a fixed number of rows. Thanks for the help.

Nodal_Coordinates =

1 0 0

2 3 0

3 6 0

4 9 0

8 0 3

7 3 3

6 6 3

5 9 3

for i = Nodal_Coordinates(:,1)

for i = 1

Node_1 = Nodal_Coordinates(i,:)

for i = 2

Node_2 = Nodal_Coordinates(i,:)

for i = 3

Node_3 = Nodal_Coordinates(i,:)

for i = 4

Node_4 = Nodal_Coordinates(i,:)

for i = 5

Node_5 = Nodal_Coordinates(i,:)

for i = 6

Node_6 = Nodal_Coordinates(i,:)

for i = 7

Node_7 = Nodal_Coordinates(i,:)

for i = 8

Node_8 = Nodal_Coordinates(i,:)

end

end

end

end

end

end

end

end

end

Turlough Hughes
on 2 Mar 2020

Tom Holz
on 2 Mar 2020

Edited: Tom Holz
on 2 Mar 2020

Something like this

for k = 1:size(Nodal_Coordinates,1)

% Find the index of the kth row

ind = find(Nodal_Coordinates(:,1) == k, 'first');

% Extract the rest of that row, skipping the first column

Node_Data = Nodal_Coordiantes(ind,2:end);

% Do what you want with that data

disp(Node_Data);

end

However, you might be able to simply this process by sorting the data first:

% Sortrows defaults to sorting by the first column in numeric order,

% and if no two rows have the same index in the first column,

% this will produce the desired result.

Nodal_Coordinates = sortrows(Nodal_Coordinates);

% Now you can just loop through the matrix and grab the data without using find().

for k = 1:size(Nodal_Coordinates,1)

ind = Nodal_Coordinates(k,1);

Node_Data = Nodal_Coordinates(k, 2:end);

end

Tom Holz
on 2 Mar 2020

I agree with Stephen. If you want to display the data, look into a function like printf:

for k = 1:size(Nodal_Coordinates,1)

ind = Nodal_Coordinates(k,1);

Node_Data = Nodal_Coordinates(k, 2:end);

fprintf('Node #%d: %s\n', ind, num2str(Node_Data));

end

If you want to reuse the data later, consider putting it into another variable, like a cell array. Cell arrays are quite versatile and are worth learning about.

nodeCount = size(Nodal_Coordinates,1);

nodes = cell(nodeCount,1);

for k = 1:nodeCount

ind = Nodal_Coordinates(k,1);

Node_Data = Nodal_Coordinates(k, 2:end);

nodes{k} = Node_Data;

end

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

Start Hunting!