Deleting elements from multiple vectors at once

조회 수: 15 (최근 30일)
dandan
dandan 2015년 9월 29일
댓글: the cyclist 2015년 9월 30일
I need to delete an element from several vectors. The inelegant way I've been doing this is:
%a=element to remove
vector1(a)=[];
vector2(a)=[];
vector3(a)=[];
...and so on. I also tried using deal:
[vector1(a), vector2(a), vector3(a)]=deal([]);
but this gives me an error ("In an assignment A(:)=B, the number of elements in A and B must be the same").
Does anyone know how to do this simply?? (I actually have a lot more than 3 vectors!)
Thanks!

채택된 답변

the cyclist
the cyclist 2015년 9월 29일
I can't think of a way to delete from several variables at once, when those variables are not components of some encompassing data object. But, the way that you are presenting this, it suggests that your variables should be contained in some object, such as a table object or dataset. (I think datasets are being phased out, so better to use a table.)
subjectid = [101 102 103 104 105]';
age = [ 37 76 23 24 65]';
iq = [ 89 101 93 116 137]';
tbl = table(subjectid,age,iq);
% Remove the second and fourth row
tbl([2 4],:) = []

추가 답변 (2개)

Jan
Jan 2015년 9월 29일
If there is a need to remove a specific element from a bunch of variables, these variables seems to have a strong relation. In this case a bunch of variables is a bad way to organize the data and problems as the described one will appear. So better store strongly related vectors in one matrix.
  댓글 수: 1
the cyclist
the cyclist 2015년 9월 30일
Jan, I agree with your statement that these variables presumably have a strong relationship, but not with your suggestion that these therefore belong in a single matrix. For example, I might have a several cars, with variables such as gasMileage, engineBlockType, weight, yearOfManufacture, etc. I don't think the correct data model for that is one big matrix. Dataset and table objects (or possibly structures) are, in my opinion, the most appropriate storage method. (This is also how most statistical software handles this.)

댓글을 달려면 로그인하십시오.


Star Strider
Star Strider 2015년 9월 29일
You didn’t say anything about the vector lengths, but if they’re all the same length, this could work:
M = [Vector1(:) Vector2(:) Vector3(:)];
M(a,:) = [];
If they’re different lengths, you would first have to create a matrix of (preferably) NaN values with a row length of the longest of them, and then write the vectors to its individual columns.
If you wanted to, you would then have to reassign the individual columns to their original vectors, but it would be best to leave them in the matrix and refer to them as matrix columns. It depends on how you’ve written your code, and how many vectors you have.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by