How to Concatenate 5 differently named variables in one variable using foor loop?

A_1=1;
A_2=2;
A_3=3;
A_4=4;
A_5=5;
for i=1:5
% now here i want to concatinate A_1 to A_5
end
Combine= [1 2 3 4 5] % this is required

4 Comments

Why you want to concatinate? While creating itself use:
A = [1 2 3 4 5] ;
V = [A_1,A_2,A_3,A_4,A_5];
But just as KSSV states, even better is to avoid these superfluous variables in the first place.
Forcing numbers into variable name is a sign that you are doing something wrong... however I suspect that this thread is going in this direction anyway:
By far the best solution is to avoid such situtations. If you wrote those variable names by hand, then simply create them in one array (numeric, cell, etc.). If those variables are created by importing data (e.g. LOAD) then LOAD into an output variable and access its fields.... etc. It is much better to avoid the situation than to try and fix the mess afterwards.
Thank you for the comments. Actually, I have n variables and every variable has a different number of elements (a row matrix). So, I need to combine all the elements of all n variables.
"Actually, I have n variables and every variable has a different number of elements (a row matrix). So, I need to combine all the elements of all n variables."
That is very easy if you have well-designed data, e.g. multiple vectors in one cell array C, using any of these:
V = [C{:}]
V = cat(n,C{:})
V = horzcat(C{:})
V = vertcat(C{:})
Trying to do that with badly-designed data (e.g. lots of variables with numbered names) will be much more complex and inefficient than that simple code. Better data design -> much better code.

Sign in to comment.

Answers (1)

a1 = 5;
a2 = 10;
a3 = 15;
combined_row_wise = [a1,a2,a3]
combined_row_wise = 1×3
5 10 15
combined_column_wise = [a1;a2;a3]
combined_column_wise = 3×1
5 10 15

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Asked:

on 12 Jan 2022

Edited:

on 12 Jan 2022

Community Treasure Hunt

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

Start Hunting!