# Dynamic array variables problems

2 Ansichten (letzte 30 Tage)
Tsz Tsun am 19 Mär. 2023
Bearbeitet: Vilém Frynta am 19 Mär. 2023
Hi all, I have some troubles in making an dynamic array. My following code is as follow but get an error.
N = 10;
for k=1:N
for j = 1:5
temp_var = strcat('v_',num2str(k));
eval(sprintf('%s = %g',temp_var(j), j*2));
end
end
Basically I want to have a dynamic array of
v_1(1) =2
v_1(2) =4
v_1(3) =6
v_1(4) =8
v_1(5) =10
v_2(1) = 2
v_2(2) = 4
etc...etc
And so when I print out v_1 it gives 2 4 6 8 10, do does v_2 , v_3 ... v_10. Would anyone offer me some help? Thanks a lot.
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Antworten (1)

Vilém Frynta am 19 Mär. 2023
Bearbeitet: Vilém Frynta am 19 Mär. 2023
You really should not do this. It's bit tricky to do and.. it will strike back later.
Better solution would be to create a structure and save your numbers there.
v = struct();
nums = 2:2:10;
v.field1 = nums;
v.field2 = nums
v = struct with fields:
field1: [2 4 6 8 10] field2: [2 4 6 8 10]
Could also be (easily) made in for loop as well.
s = struct();
for q = 1:10
s.(sprintf('field%d',q)) = nums;
end
disp(s)
field1: [2 4 6 8 10] field2: [2 4 6 8 10] field3: [2 4 6 8 10] field4: [2 4 6 8 10] field5: [2 4 6 8 10] field6: [2 4 6 8 10] field7: [2 4 6 8 10] field8: [2 4 6 8 10] field9: [2 4 6 8 10] field10: [2 4 6 8 10]
##### 0 Kommentare-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Find more on Data Types in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by