Append results into an array in a for loop as in python
8 views (last 30 days)
Show older comments
Reuben Addison
on 1 Apr 2023
Answered: Cris LaPierre
on 1 Apr 2023
I created an array to store results from a for loop, looks like it seems to break
vertices = zeros(length(Data.X3),1);
for i = 1:length(Data.X3)
[vertices(i), ~]= Vertex([Data.X3(i); Data.Y3(i); Data.Z3(i)])
end
But I am not getting the desured results
6 Comments
dpb
on 1 Apr 2023
Besides @Cris LaPierre's Q?, what is the content of Data.X, ...? Is it actually the data itself or an index into the data? As written, the expression [Data.X3(i);Data.Y3(i);Data.Z3(i)] creates a column 3-vector and making the assumption that Vertex() is an array, then each call will return a 3-vector of the values at those indices, if they are indeed valid indices into the array. If they're actually values instead, then "Boom!"; either likely will be indices outside the range of the array or invalid floating point values attempted to be used an indices.
On the LHS, the "~" tells MATLAB to throw away any second returned value from a function call and the single index (i) on the preallocated array is attempting to store three elements into a single location, so that is bad syntax from multiple points of view.
IF the Data structure elements are indeed valid indices into the Vertex array, then the output vector size must be 3X the size of each of those if the idea is to concatenate all into one long column array; given that it is preallocated only to that size vertically and by the use of a second element in the LHS expression, I'm guessing the intent was to produce a 2D array of the X,Y,Z locations. If that is the case, and also guessing that the "3" on the stuctuure names implies a 3D array, then "the MATLAB way" using vectorized operations would simply be
vertices=[Vertex(Data.X3, Data.Y3,Data.Z];
The above makes lots of assumptions, but without the details of what really have, it's about best can make a stab at -- other than the syntax issues.
Accepted Answer
Cris LaPierre
on 1 Apr 2023
Not sure what the desired results are, but here's a sample of your code. It works as I'd expect. Perhaps you can be more clear on what is not working for you.
% Make up some data
X3 = rand(10,1);
Y3 = rand(10,1);
Z3 = rand(10,1);
Data = table(X3,Y3,Z3)
% your original code
vertices = zeros(length(Data.X3),1);
for i = 1:length(Data.X3)
[vertices(i), ~]= Vertex([Data.X3(i); Data.Y3(i); Data.Z3(i)]);
end
% View results
vertices
% made up function for demonstration purposes
function [vertex_number, vertex_coord] = Vertex(D);
[vertex_coord, vertex_number] = max(D);
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!