Remove columns from a matrix with a loop.
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi, I know I posted this a couple of days ago, and the info really helped, this is just a continuation of the question with my code posted.
I am graphing data from different databases, and sometimes the data is missing. In this case, instead of a double array, the data is a string 'No Data'. I am writing a loop to delete columns with this string in place of the data. I need to delete the column from the dataarray that holds the data, and the namearray that holds the names of the data. They are both 1 by n cell arrays.
What I have now:
for i=1:length(dataarray) %Length of the data array
if strcmp(dataarray{i},'No Data')
%Sees if the column of the data array has no data
namearray(:,i)=[];
%Deletes the name for which there is no data
dataarray(:,i)=[];
%Deletes the column that has no data
end
end
Now this works like a charm when there is one column that has no data. However, it fails when there is more than one.
I get: ??? Index exceeds matrix dimensions.
Error in ==>>
If strcmp(dataarray{i},'No Data'}
I am not really sure why I am getting this error. I know with loops each iteration moves the reference frame of the number deleted. (So like if the first column is deleted on the first repetition of the loop, now the second column becomes the first column).
Thanks for any help! I have been playing with this all morning, and I am not sure the best way to accomplish this is.
0 comentarios
Respuesta aceptada
Sean de Wolski
el 8 de Jun. de 2011
Once you delete a column your matrix is smaller so the last entry (length(dataarray)) no longer exists.
The easiest remediation for this is to run it backwards!
It would still be best if you create an index list of all of the columns you need to remove and then do it all at once. E.g. something like:
idx = cellfun(@(x)strcmp(x,'No Data'),dataarray);
dataarray(:,idx) = [];
3 comentarios
Más respuestas (2)
Matt Fig
el 8 de Jun. de 2011
The reason why you should not use a FOR loop for this is that you set the loop to iterate over the original length of the variable. Then if you delete a value in the variable, the length of the variable decreases, but the loop will keep right on going.
Did you read this? Did you try the example I gave and think about the problem???
Use CELLFUN.
DA = {'No Data',magic(3),'No Data',[1 2 3],[6 6 6 6],'No Data'};
idx = cellfun(@(x) strcmp(x,'No Data'),DA);
DA = DA(~idx)
2 comentarios
Fangjun Jiang
el 8 de Jun. de 2011
You ignored the caution both Matt and I gave you in your previous question. You should not do it in the loop.
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!