Concatenate into a matrix is not saving and is overriding every iteration?

1 view (last 30 days)
I have 2 subjects where each subject has three conditions. I made an array where each row is 1*3 representing one subject with the three conditions. I now want to add each subjects' array together.
However, my code seems to be overwriting every round, when I want:
%subject 1
percent_change = [1 2 3]
%subject 2
percent_change = [3 4 5]
%what I want as ouput:
percent_change_matrix: 1 2 3
3 4 5
Here is what I have tried:
%try 1
subjs = {'subject1' 'subject2'}
time = {'30-50' '50-60' '60-70'}
%% defining tac components for pet plot
for s = 1:length(subjs)
subj = subjs{s}
for i = 1:length(time)
time = time{i}
percent_change(:,i) = ((task-baseline)/baseline)*100 %task=2 baseline=1
end
percent_change_matrix = []
percent_change_matrix = [percent_change_matrix; percent_change]
end
I have also tried:
%try 2
subjs = {'subject1' 'subject2'}
time = {'30-50' '50-60' '60-70'}
%% defining tac components for pet plot
for s = 1:length(subjs)
subj = subjs{s}
for i = 1:length(time)
time = time{i}
percent_change(:,i) = ((task-baseline)/baseline)*100
end
try
percent_change_matrix = [percent_change_matrix; percent_change]
catch
percent_change_matrix = [percent_change_matrix]
end
end
my output for try 1 and try2 is:
percent_change_matrix: [3 4 5]
There are no errors with eithor of my codes, but the matrixes are not being built upon eachother. Do you have any suggestions? Thanks so much!
  7 Comments
nines
nines on 14 Jun 2022
Edited: nines on 14 Jun 2022
task and baseline are each going to be equal to one number for each subject and time combination:
here are examples:
subject 1, time 30-50: task: 2, baseline: 1
subject 1, time 50-60: task: 3, baseline: 2
subject 1, time 60-70: task: 3, baseline: 2
subject 2, time 30-50: task: 2, baseline: 1
subject 2, time 50-60: task: 4, baseline: 3
subject 2, time 60-70: task: 5, baseline: 2
Ganesh
Ganesh on 14 Jun 2022
The issue is that percent_change_matrix is being redefined to an empty array at every iteration for subject. Move the declaration of this to the beginning, or immediately following 'time' variable.
Another issue that may arise seems to be
time = time{i}
This would redefine your time variable. Consider naming one of the variables differently.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 14 Jun 2022
Edited: Matt J on 14 Jun 2022
Ns=numel(subjs); Nt=numel(time);
percent_change=cell(Ns,1);
for s = 1:Ns
subj = subjs{s};
for i = Nt:-1:1
...
percent_change{s}(:,i) = ((task-baseline)/baseline)*100 %task=2 baseline=1
end
end
percent_change_matrix=cell2mat(percent_change);

More Answers (0)

Categories

Find more on Data Distribution Plots 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!