Selectivly remove values from a matrix with a loop

7 ビュー (過去 30 日間)
daniel.x16
daniel.x16 2011 年 6 月 6 日
I wrote a program that takes data from different databases and plots them. However, sometimes one or more of the databases inputting data yields no values from a query.
When this happens, I get an error message,
'index exceeds matrix dimensions'
Right now, my guess on how to solve this is to run a 'for' loop. (I want to remove the null set of data from a data array as well as a 'names' array (for the plot legend))
I have n data sets and a names array with n names.
I want to do:
for i=1:n %Check each database
if dataarray{i}=0
%If the data is null (This might not be the right way to do this...but basically if there IS data...it is stored as a 350x2 double array...and if there is NOT data...its stored as 0 (a double array I believe)
delete ith value from dataarray
%I dont know how to do this
delete ith value from namesarray
%Also dont know how to do this
n=n-1
%For plotting in the future..we have one less dataset..now n-1 datasets
end
end
So thats what I am trying to accomplish. I have been trying to read about error handling from matlab, and have also browsed this forum, but cannot find exactly what I need.
Any help would be great!

採用された回答

Matt Fig
Matt Fig 2011 年 6 月 6 日
It looks like you are using a cell array.
dataarray = {9, [8 8;9 9], 7, 0, [5 9], 0, magic(2), 0, 'string'}
dataarray = dataarray(~cellfun(@(x) isequal(x,0),dataarray))
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. Here is a simple example to follow:
A = [1 2 3 4];
for ii = 1:length(A) % ii is going to 4, unless an error occurs...
ii % Display current value of ii
A(ii) = [] % What will happen when ii is 3??
end

その他の回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2011 年 6 月 6 日
Follow this example:
a=1:9
a(5)=[]
Please note that using this approach, you should not do it in a loop. Also follow this example:
b=randint(5)
b(b==0)=[]
  5 件のコメント
Fangjun Jiang
Fangjun Jiang 2011 年 6 月 6 日
The reason not to do it in the loop is because a(5)=[] as an example above reduces the length of a from 9 to 8. Thus if it is in a for-loop (for i=1:9), it will mess up with the index. If you don't want to remove that element, you can assign a special value like inf or nan. Anyway, maybe you should provide an example with some data so we'll better understand the question and provide answers.
Walter Roberson
Walter Roberson 2011 年 12 月 8 日
daniel.x16: there is no such thing as an if loop.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by