How to locate and extract elements from a matrix?

90 views (last 30 days)
Hi, I need to locate specific elements in each column of a matrix and print them in a new column matrix. For example if I have a 6x4 matrix
A = [a1 b1 c1 d1;
a2 b2 c2 d2;
a3 b3 c3 d3;
a4 b4 c4 d4;
a5 b5 c5 d5;
a6 b6 c6 d6]
I should locate some elements from the first column of matrix A, and print them into two new column matrices B and C. The first column of matrix A is a1, a2, a3, a4, a5, a6
My new matrix B should take these elements: a1, a2, a3, a4, so
B = [a1; a2; a3; a4]
After that I should define new matrix C, which will take elements a3, a4, a5, a6, so
C = [a3; a4; a5; a6]
This process I need to repeat for every column of matrix A. Does anyone have tips how to do this? Thanks!
  4 Comments
EB
EB on 18 Dec 2015
The rules are that every new matrix, e.g. B and C are column matrices built from first column of A, they need to have four elements, and two first elements of matrix C are the last two elements of B. So, for this example, first column of A gives my column matrices B and C, the 2nd column gives me column matrices D and E, 3rd column gives me F and G, the 4th column gives me H and I. The elements I need to locate for B are A(1), A(2), A(3), A(4), for C are A(3), A(4), A(5), A(6), for D are A(7), A(8), A(9), A(10), for E are A(9), A(10), A(11), A(12), for F are A(13), A(14), A(15), A(16), for G are A(15), A(16), A(17), A(18), for H are A(19), A(20), A(21), A(22) and for I are A(21), A(22), A(23), A(24) etc. All the elements of A are defined in advance. I know that I can define these new matrices by just assigning manually a's to B's, C's, D's, E's etc. Is there a shortcut to write this extraction for every column of A? Because, what if I have a larger matrix A, e.g. 22x22, then I have 22 elements in one column.
Image Analyst
Image Analyst on 18 Dec 2015
You've accepted harjeet's answer so we'll assume that his code does the rules you gave above and the problem is now solved.

Sign in to comment.

Accepted Answer

harjeet singh
harjeet singh on 17 Dec 2015
try this
clear all
close all
clc
A=randint(6,4,[1 100])
for i=1:size(A,2)
o=A(:,i);
B=o(1:4)'
C=o(3:6)'
end

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!