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!