MATLAB: Keeping the same order in arrays – Brain Teaser

arraymatrixmatrix manipulationvector

**EDIT: I need the output to be a matrix because a much larger part of the code needs the output of this code to be a matrix for it's input****
Hello. I have a question related to matrix manipulation.
I need to keep the order the same in the matrix. Please see below for what I am trying to do.
lets say I start out with 3 fruits:
fruits = {'apple','orange','berry'};
and the amounts of each fruit:
amount = [3,5,2]
then the next day the amount changes:
amount = [2,4,3]
so now, my matrix will be:
3 5 2
2 4 3
but what if the next day I needed to add another fruit:
fruits = {'apple','orange','berry','banana'};
and the amounts are:
amount = [3,4,2,1]
how do I make my new matrix like this:
3 5 2 NaN
2 4 3 NaN
3 4 2 1
then on the next day, I was not given 1 of the original fruits:
fruits = {'apple','berry','banana'};
and the amount would be:
amount = [5,1,4]
then I need the matrix to be like the following:
3 5 2 NaN
2 4 3 NaN
3 4 2 1
5 NaN 1 4
How would I write the code for it to be able to handle all of these situations?

Best Answer

Try using a non-scalar structure (note that looping backwards is useful and not a mistake)
fruits{4} = {'apple','berry','banana'};
amount{4} = [5,1,4];
fruits{3} = {'apple','orange','berry','banana'};
amount{3} = [3,4,2,1];
fruits{2} = {'apple','orange','berry'};
amount{2} = [2,4,3];
fruits{1} = {'apple','orange','berry'};
amount{1} = [3,5,2];
for mm = numel(fruits):-1:1 % backwards!
for nn = 1:numel(fruits{mm})
out(mm).(fruits{mm}{nn}) = amount{mm}(nn);
end
end
And we can view the data:
>> {out.apple}
ans =
[3] [2] [3] [5]
>> {out.banana}
ans =
[] [] [1] [4]
Note the missing data are indicated by empty arrays.