MATLAB Answers

Kel
0

How to index a matrix using the ITERATION values of a valArray with non-consecutive numbers?

Asked by Kel
on 3 Jan 2018
Latest activity Commented on by Kel
on 5 Jan 2018
Hi everyone, New to matlab here and I can't seem to find a previous answer to this question.
I'm trying to populate a matrix element by element using a for loop, but I'm running into a problem. Because of the way I need it to load in the data, I have the subject numbers listed in a valArray for the for loop. This works fine for loading, but when I try to index the matrix, it puts it the value in the element of the actual VALUE of the number, whereas I want it to be in the element of the iteration number it represents. Here's what I have:
for s = [1297 1304]
for b = 1:2
datafilename=sprintf('none_mod_part_data_gamma1.25_%d_Block%03d.mat',s,b);
%datafile=[datadir,datafilename];
load(datafilename);
GE_byblock(b)= GE_pos(1);
LE_byblock(b)=mean(LE_pos{1});
...
end;
LE_allsubs_avg(s) = mean(LE_byblock);
LE_allsubs_std(s) = std(LE_byblock);
GE_pos_allsubs_avg(s) = mean(GE_byblock);
GE_pos_allsubs_std(s) = std(GE_byblock);
...
end;
So what I want is for the value I have produced for subject 1297 to go in element ONE of the LE_allsubs_avg matrix and the value for subject 1304 to go in element TWO of the allsubs matrix, etc. But what I get is the value for subject 1297 going into element 1297 of the allsubs matrix. Any way I can remedy this, or do I have to make a new loop somehow with i=1:number of subjects?
Additionally, I have previously in the code initialized all the matrices to their correct sizes.
Thanks so much- any help is greatly appreciated!!!

  0 Comments

Sign in to comment.

1 Answer

Answer by Kelly Kearney
on 3 Jan 2018
 Accepted Answer

There are two ways you could do this. One is to use an index value corresponding to the length of your s values:
s = [1297 1304]
for is = 1:length(s)
% ... code here, replacing previous s with s(is)
LE_allsubs_avg(is) = ...
end
Alternatively, you could add a counter variable:
count = 1;
for s = [1297 1307]
% code here
LE_allsubs_avg(count) = ...
count = count + 1
end

  1 Comment

This worked perfectly! Thank you so much for your help, I really appreciate it!

Sign in to comment.