MATLAB: Is there any way to convert variables from list to arrays
cell2numstr2num
I have 2 arrays
a = [1 2 3]
b = [2 3 4]
and a list
c = {'a', 'b'}
when I use cell2mat(c(1,1)), I get a, but what I want is [1 2 3]. Is there any way to achieve it?
Best Answer
Simply store the data inone structure, and then it is trivially easy (no slow, buggyeval is required):
>> S.a = [1,2,3];
>> S.b = [2,3,4];
>> C = {'a','b'};
>> S.(C{1})
ans =
1 2 3
Simpler code through better code design: faster, neater, simpler, more efficient, easiest to debug, less complex. Why waste your time learning bad ways to write code?:
This would actually be horribly slow, pointlessly complex, obfuscated, and very buggy way to write your code. You would make your code hard to debug, and a pain to work with. Read this to know why:
Usingindexing would be simple, neat, and very efficient. You should useone array andindexing.Indexing is the solution you should be using, because it is the most efficient way to write MATLAB code, is simple, neat, and very easy to debug.Indexing is explained quite well in the MATLAB introductory tutorials, which are highly recommended for all beginners:
Easy, given any number of arrays in a cell arrayC. You could use a loop like this, although it is inefficient because theoutput array is not preallocated:
C = {[1,2],[3,4],...} % cell array of arrays.
A = C{1};
for k = 2:numel(C)
A = [A;C{k}];
end
Simpler and more efficient would be to concatenate them all at once, without a loop, e.g.:
A = vertcat(C{:})
Whatever you do, do NOT try to access variable names dynamically in a loop! Read this to know why:
Best Answer