Reputation: 37
I would like to create something to store string, for example:
for x = 1:3
fruit = strcat('orange', num2str(x));
A = {fruit};
how can I make an output of a 1x3 matrix of
A =
orange1
orange2
orange3
I have tried a few things but nothing worked.
I do not think it is complicated, but I just don't seem to get my head round it.
and after I completed this, would I be able to combine a normal numerical matrix with A such that:
N = [1 2; 3 4; 5 6];
FINAL = [N A];
>>output of FINAL would look like
FINAL =
1 2 orange1
3 4 orange2
5 6 orange3
Upvotes: 0
Views: 135
Reputation: 12345
for x = 1:3
fruit = ['orange', num2str(x)];
A{x,1} = fruit;
end
N = [1 2; 3 4; 5 6];
N_as_cell = num2cell(N);
FINAL = cat(2, N_as_cell, A);
Upvotes: 0
Reputation: 71
In MatLab, numerical arrays can only be concatenated with numerical arrays. If you want to create an array with varying data types, you need to use Cell Arrays.
To answer your first question, I would advise you to first declare fruit as a cell array, and then fill it with the desired data :
fruit = cell(3,1);
for i =1:3
fruit{i} = strcat('orange',num2str(i));
end
fruit
This should produce the desired output.
For your second question, if you want to concatenate a numerical array with a cell array, you first need to convert it to a cell array using num2cell, such as :
N = [1 2;3 4;5 6];
FINAL = [num2cell(N),fruit]
In that case, FINAL will be an array of 9 cells, that you could access like FINAL{1,3} = orange1. To write compact code with cells, you should take a look at cellfun and deal which are two useful functions.
Hope this helps !
Upvotes: 4