Keeping the same order in arrays - Brain Teaser?
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
Ingrid
on 23 Jun 2015
is there any particular reason why you would want this in matrix format?
are you aware of the possibility to use structures in matlab with dynamic indexing? than you would do something like this for each time t:
for ii = 1:numel(field(fruits))
if isfield(countingFruits.(fruits)
countingFruits.(fruits{ii}) = [countingFruits.(fruits{ii}); t, amount];
else
countingFruits.(fruits{ii}) = [t,amount(ii)];
end
end
you need to save the t to later be able to construct NaN for missing t's
Viral Solanki
on 23 Jun 2015
Viral Solanki
on 23 Jun 2015
Accepted Answer
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.
1 Comment
Viral Solanki
on 23 Jun 2015
Categories
Find more on Structures 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!