How to remove columns from matrix?
2 ビュー (過去 30 日間)
古いコメントを表示
I have a matrix A and I want to remove from this matrix each column that contain the value -1.
A= [-1.192 -1.020 -1 -1.050 -1 -1 -1.070;
-1.213 -1.096 -1 -1.045 -1 -1 -1.102;
-1.036 -1.061 -1 -1.085 -1 -1 -1.137;
-1.176 -1.120 -1 -1.004 -1 -1 -1.115;
-1.124 -1.034 -1 -1.073 -1 -1 -1.134;
-1.202 -1.145 -1 -1.078 -1 -1 -1.057;
-1.127 -1.023 -1 -1.056 -1 -1 -1.066]
the size of A is 7*7 and I want to have a matrix 7*4 after removing colums? How can I do please?
0 件のコメント
採用された回答
Star Strider
2015 年 4 月 15 日
A more general solution:
A = reshape(A(~arrayfun(@isequal, A, -ones(size(A)))),size(A,1),[]);
It first finds a logical array of vectors that are equal to -1 using arrayfun, takes the values of the matrix that are not those values and creates a new vector from them. It then takes that vector and reshapes it to the row size of the original matrix to create the new ‘A’ matrix.
5 件のコメント
Star Strider
2015 年 4 月 15 日
Did you try it yourself to see what it does? (My code does a version of what you intend with that.)
BTW, I always test my code to be sure it works before I post it (or clearly label it ‘untested code’ if I can’t). It saves time and enhances credibility.
pfb
2015 年 4 月 15 日
I did test it. Here is what I get
>> A = [-1 2 -1 3 -1; 2 -1 -1 0 1];
>> A==-ones(size(A))
ans =
1 0 1 0 1
0 1 1 0 0
>> arrayfun(@isequal, A, -ones(size(A)))
ans =
1 0 1 0 1
0 1 1 0 0
It seems to me that they are equivalent, at least for this minimal example. I jotted down the matrix randomly, making sure that at least one column was composed of -1 alone. Maybe I was lucky. I have to admit I did not embark in systematic testing. Anyway, that is why I asked.
その他の回答 (3 件)
N/A
2015 年 4 月 15 日
編集済み: N/A
2015 年 4 月 16 日
% A(:, any(A == -1)) = [] %% Please try this.
% revised 'any' to 'all'. 'any' means the columns in which there is any '-1'; 'all'means the columns in which they are all '-1'.
A(:, all(A == -1)) = []
2 件のコメント
James Tursa
2015 年 4 月 15 日
"all" instead of "any" to achieve the goal "... remove columns that entirely contain the value -1 ..."
Sahar abdalah
2015 年 4 月 15 日
3 件のコメント
Star Strider
2015 年 4 月 15 日
What do you mean by ‘remove the index’? The resulting matrix will be smaller, so you will have to address its columns differently than you did in the original matrix. You will have to rewrite your code to do that.
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!