How to access a element of a dynamically created array
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi all, I have created a set of arrays of dimension 1*3 using the following code :
BS = 3; area = 300;
X1 = area * rand(1,BS) -area/2 ;
Y1 = area * rand(1,BS) -area/2 ;
for i = 1:BS
eval(['BS' num2str(i) '= [X1(i) Y1(i) 1] '])
end
and i would like to dynamically access the third element of BS"i". Let's say that BS1(3) = 100, and BS2(3) = 150 and BS3(3) = -200. How I would realize that dynamically by using a for loop ?
댓글 수: 1
채택된 답변
DGM
2022년 4월 12일
Just use an array
BS = 3;
area = 300;
BSx = [area*(rand(BS,2) - 0.5) ones(BS,1)]
댓글 수: 3
DGM
2022년 4월 13일
I never said it couldn't be done; I said it was unnecessary. You're defeating the most basic functionality of the language by embedding indexing information into the variable name.
Accessing the row vectors within a matrix is easier, faster (by about three orders of magnitude), and more flexible than doing the same with a bunch of dynamically accessed named vectors.
BS = 3;
area = 300;
BSx = [area*(rand(BS,2) - 0.5) ones(BS,1)]
You want the first element of the second vector?
BSx(2,1)
Want the third vector in whole?
BSx(3,:)
Want all x values?
BSx(:,1)
It's your choice.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Develop Apps Using App Designer에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!