Deleting elements from multiple vectors at once
8 次查看(过去 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!
0 个评论
采纳的回答
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],:) = []
0 个评论
更多回答(2 个)
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
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
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!