Append results into an array in a for loop as in python
14 次查看(过去 30 天)
显示 更早的评论
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 个评论
dpb
2023-4-1
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.
采纳的回答
Cris LaPierre
2023-4-1
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!