user5603723
user5603723

Reputation: 193

Creating an array with characters and incrementing numbers

Pretty simple problem, I want to create an array with char in a for loop.

code:

a = [1:5];
arr = [];
for i = 1:length(a)
    arr(i) = ['f_',num2str(i)]
end

I am getting error:

In an assignment  A(I) = B, the number of elements in B and I must be the same.

all i want is an array:

[f_1 f_2 f_3....]

Upvotes: 1

Views: 69

Answers (1)

Stewie Griffin
Stewie Griffin

Reputation: 14939

This is because arr(i) is a single element, while ['f:', num2str(i)] contain three characters. Also, for i = 1:length(1) doesn't really make sense, since length(1) is guaranteed to be 1. I guess you wanted for i = 1:length(a). If that's the case I suggest you substitute length with numel and i with ii.

The better way to create the array you want is using sprintf like this:

sprintf('f_%i\n',1:5)
ans =
f_1
f_2
f_3
f_4
f_5

Or possiblby:

sprintf('f_%i ',1:5)    
ans =    
f_1 f_2 f_3 f_4 f_5 

I guess this is what you really wanted:

for ii = 1:5
    arr{ii} = ['f_', num2str(ii)];
end
arr =     
    'f_1'    'f_2'    'f_3'    'f_4'    'f_5'

Or simpler:

arr = arrayfun(@(n) sprintf('f_%i', n), 1:5, 'UniformOutput', false)

The last two can be indexed as follows:

arr{1}    
ans =    
f_1

You can also do (same result):

str = sprintf('f_%i\n', 1:5);
arr = strsplit(str(1:end-1), '\n')

If you're doing this to create variable names, then please don't. Use cells or structs instead.

Upvotes: 3

Related Questions