Deleting elements from multiple vectors at once
Mostra commenti meno recenti
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!
Risposta accettata
Più risposte (2)
Jan
il 29 Set 2015
1 voto
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 Commento
the cyclist
il 30 Set 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
il 29 Set 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.
Categorie
Scopri di più su Multidimensional Arrays in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!