Deleting elements from multiple vectors at once
1 view (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
the cyclist
on 29 Sep 2015
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],:) = []
0 Comments
More Answers (2)
Jan
on 29 Sep 2015
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 Comment
the cyclist
on 30 Sep 2015
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
on 29 Sep 2015
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.
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!