Keeping the same order in arrays - Brain Teaser?
1 view (last 30 days)
Show older comments
**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?
3 Comments
Accepted Answer
Stephen23
on 23 Jun 2015
Edited: Stephen23
on 23 Jun 2015
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.
4 Comments
More Answers (1)
Steven Lord
on 23 Jun 2015
Try using a table.
t = array2table([3 5 2], 'VariableNames', {'apple','orange','berry'});
t(end+1, {'apple', 'orange', 'berry'}) = {2, 4, 3};
t(end+1, {'apple', 'orange', 'berry', 'banana'}) = {3, 4, 2, 1};
t(end+1, {'apple', 'berry', 'banana'}) = {5, 1, 4};
This will give you a warning on the last line, but if you intentionally did not assign to the orange variable you can suppress it. It will also fill in with 0's instead of NaN but you can use standardizeMissing to replace 0 with NaN. See the examples in the table documentation for more information on how to work with this data type.
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!