Indexing through a cell array

I am looking to populate cell array named 'age_list' based on the values i have in two columns; named 'day' and 'pop'
  • For each specific 'day', i am looking at the corresponding 'pop' value and then update the 'age_list' based on it.
  • Example: On day 4, the population is 3. Therefore the cell array 'age_list' will have 'three' values with the {2,3,4}.
Can anyone suggest me on how to perform this? Any help will be appreciated.

6 Comments

I have no idea how you are obtaining the values in age_list from day and pop. A better explanation is needed for me.
I will try to explain using an example. Please let me know if its unclear.
Example : If we look at the day 2, the population is 2, so it means in the 'age_list' there will be two values. For the specific case on day 2, the values in the age_list will be {1,2} . This is because there is a population increment in day 2, so the age list will have a value 1. It will also have a value 2, from the population on the previous day.
The question is not clear yet. The inputs are:
day = 1:7;
pop = [1,2,3,3,3,4,6];
How do you get the output age_list{6} = [1,1,2,5,6,7] ? Why is age_list{6} = [1,4,5,6] ?
In the age_list{6} = [1,4,5,6], the population is 4 and the corresponding day is 6.
In the age_list{7}, the corresponding day is 7 and the population becomes 6. So there is an increment in population by 2, on day 7. Therefore in the age_list{7}, there will be two more new individuals with age {1,1} along side the updated age of the other individuals {2,5,6,7}. so age_list{7} = [1,1,2,5,6,7]
Jan
Jan on 23 Sep 2021
Edited: Jan on 23 Sep 2021
Is day in all cases 1:numel(day) ? Can the population size shrink? Is {1} a fixed startpoint?
Yes, day in all cases is 1:numel(day).
The population size cannot shrink.
{1} is a fixed starting point.

Sign in to comment.

 Accepted Answer

A bold try:
day = 1:7;
pop = [1,2,3,3,3,4,6];
age_list = cell(1, numel(day));
age_list{1} = 1; % Is this given?!
for k = 2:numel(day)
new = pop(k) - pop(k - 1);
age_list{k} = cat(2, repmat(age_list{1}, 1, new), age_list{k-1} + 1);
end
age_list
age_list = 1×7 cell array
{[1]} {[1 2]} {[1 2 3]} {[2 3 4]} {[3 4 5]} {[1 4 5 6]} {[1 1 2 5 6 7]}

2 Comments

Thank you very much for the suggestion.
I would like to clarify an issue, if the length of days and pop is not equal, how will this work.
For example;
day = 1:178;
pop = [2,30,30,37,39,55,69,70,72,77,78,78,89,90,96,98,98,103,103,106,107,121,178];
I cannot guess, what you expect as output in this case.

Sign in to comment.

More Answers (0)

Asked:

on 23 Sep 2021

Commented:

Jan
on 23 Sep 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!