Extract numbers from Matrix and create a matrix

1 回表示 (過去 30 日間)
Johnny
Johnny 2014 年 1 月 25 日
コメント済み: Amit 2014 年 1 月 26 日
An M-by-M matrix X is given. Without using loops, extract values from matrix X to create the following:
%Generate an MxM matrix X. For part iv), X must have an even number of rows %and columns.
M = randi([20 40], 1);
M = M + mod(M,2);
X = magic(M);
===================================================
Maybe I just don't understand the problem.. how do I create a matrix for problem A, the dimension of matrix A is not given?
This is what I got for A, Is there a better answer than
A = a(:,1:2:end);
for problem A?
=====================================================
Any body knows how to do B and C, I need some hints

採用された回答

Amit
Amit 2014 年 1 月 25 日
編集済み: Amit 2014 年 1 月 25 日
For problem A, you are looking for odd rows and column, so the indexes should go for 1 with an increment of 2.
Like
A = X(1:2:end,1:2:end); % end simply represents the end
For B: you are excluding the first and last, so the indexes should exclude those.
B = X(2:end-1,2:end-1);
For C, I'd say first write down the indexes you're looking for on a piece of paper and see if you see a pattern. Post, even if it is wrong, and I'll tell you how to do it.
Sometimes it is easy to write out on a a piece of paper the indexes because it help you visualize.
  3 件のコメント
Johnny
Johnny 2014 年 1 月 26 日
Amit
Amit 2014 年 1 月 26 日
So you figure it out?

サインインしてコメントする。

その他の回答 (1 件)

Johnny
Johnny 2014 年 1 月 26 日
編集済み: Johnny 2014 年 1 月 26 日
My answer for C :
firstRow = diag(ans, 1)'
secondRow = diag(ans, -1)'
C = [firstRow; secondRow]
Although it works. Probably not the most efficient way to do this. Any suggestions?
  1 件のコメント
Amit
Amit 2014 年 1 月 26 日
Your solution is a very good solution. I am glad you figured out diag. Other way would be: Lets say its a 5X5 matrix
C = [X(2:6:end)' X(6:6:end)'] % This method uses Linear indexing
Good luck in your studies and I hope you learn significantly about MATLAB Programming :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by