How to access a element of a dynamically created array

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 comentario

DGM
DGM el 12 de Abr. de 2022
Editada: DGM el 12 de Abr. de 2022
You know what's better than solving an unnecessary problem?
Not creating the problem in the first place.
Side note: There's not much point accessing BSx(3). You explicitly set them all to 1.

Iniciar sesión para comentar.

 Respuesta aceptada

Just use an array
BS = 3;
area = 300;
BSx = [area*(rand(BS,2) - 0.5) ones(BS,1)]
BSx = 3×3
49.0217 81.9383 1.0000 -61.5512 72.0274 1.0000 -98.1272 -102.9906 1.0000

3 comentarios

thank you for your replay, but i wanted to have each line of the created array BSx in a separated variable, because i will use each one of them later. Anyways I found a solution in order to access a specific element with the created variables using for loop that i mentioned earilier, and the solution is in fact :
eval(['BS' num2str(i) '(3) '])
with this line of code I'm accessing the third element of the each BS"i", for instance : BS1(3) = 1 and BS2(3) = 1 and BS3(3) = 1
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)]
BSx = 3×3
58.9408 15.3944 1.0000 -64.1582 65.8407 1.0000 -81.9446 -23.0681 1.0000
You want the first element of the second vector?
BSx(2,1)
ans = -64.1582
Want the third vector in whole?
BSx(3,:)
ans = 1×3
-81.9446 -23.0681 1.0000
Want all x values?
BSx(:,1)
ans = 3×1
58.9408 -64.1582 -81.9446
It's your choice.
Yes I saw what you meant. Thank you so much for your reply anyways ;)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Preguntada:

el 12 de Abr. de 2022

Comentada:

el 13 de Abr. de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by