MATLAB Answers

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

15 views (last 30 days)
Kel on 3 Jan 2018
Commented: 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
GE_byblock(b)= GE_pos(1);
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);
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!!!


Sign in to comment.

Accepted Answer

Kelly Kearney
Kelly Kearney on 3 Jan 2018
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) = ...
Alternatively, you could add a counter variable:
count = 1;
for s = [1297 1307]
% code here
LE_allsubs_avg(count) = ...
count = count + 1

More Answers (0)

Community Treasure Hunt

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

Start Hunting!