How to assign proper index within a for loop?

2 views (last 30 days)
Ali Y.
Ali Y. on 18 Jul 2015
Edited: Azzi Abdelmalek on 18 Jul 2015
Hi, How can I assign proper index within 'for loops', so that I reach to values of all loops? For example, I have a matrix as following; and I want to divide it to two separate matrices. I know I should have two matrices (TA) with dimension: (r=7,c=3) and (r=5,c=3). But I only get the result of last loop , i.e. TA(end). How should I assign proper index at left hand of assignment to get the result of all loops? In this case, I tried TA (c,r,i), so that each matrix get stored in relative (i.e. i) dimension, but it gives an error message "Assignment has more non-singleton rhs dimensions than non-singleton subscripts". Could someone please help me solve and understand this chronic problem of mine?
Thank you in advance
clear all
clc
A1 = [1;1;1;2;2;2;3;3;3;4;4;4];
A2= [1;1;1;1;1;1;1;2;2;2;2;2];
A3 = (10:10:120); A3 = A3';
A = [A1,A2,A3];
b = min(A2): max(A2);
for i = min(b): max(b)
TA = A((find(A2 == b(i))),:);
[r,c] = size(TA)
TA = A((find(A2 == b(i))),:)
end
  2 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 18 Jul 2015
Edited: Azzi Abdelmalek on 18 Jul 2015
I tested your code, no error message
Ali Y.
Ali Y. on 18 Jul 2015
Dear Azzi, thank you for your reply, the error arise when the last line of the loop is written as
TA((r,c,i) = A((find(A2 == b(i))),:)
I need to assign TA an index to get the two matrix, when I recall TA outside of the for loop.

Sign in to comment.

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 18 Jul 2015
Edited: Azzi Abdelmalek on 18 Jul 2015
You can't do
TA((r,c,i) = A((find(A2 == b(i))),:)
Because find(A2 == b(i)) will return different sizes. but you can use cell array
TA{i} = A((find(A2 == b(i))),:)
To get your matrices
TA{1}
TA{2}

Community Treasure Hunt

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

Start Hunting!