[英]How to write a for loop as a condition of a while loop in MATLAB?
[英]How to convert while loop into for loop in matlab?
i=1;
while i:length(array)
if (array(i)<=1000)
array(i)=[];
else
i=i+1;
end
end
這是一個matlab代碼。 可以任何身體告訴我如何將其轉換為for循環。
你實際上不需要循環; 您可以使用MatLab索引屬性刪除元素“<= 1000”:
array(array <= 1000)=[]
編輯以回答評論中的問題
通過索引屬性從另一個數組中刪除其他元素
要刪除與第一個數組中要刪除的數組位於同一位置的另一個數組的元素,必須存儲這些位置索引,然后使用它們來尋址第二個數組的元素:
當您在第一個數組中查找索引時,可以將它們評估為logical
索引或double
索引:
說明:
logical_idx=array <= 1000;
返回logical
類型的數組logical_idx
,即
- 如果條件得到驗證,則為1
- 如果不是,則為0
函數find
可用於“查找”滿足條件的數組元素:
double_idx=find(array <= 1000)
在這種情況下,返回的數組是double
類型。
使用logical
索引訪問數組元素時,選定的元素與邏輯數組中的1
對應。 例如,如果logical
索引數組是:
[0 1 1 0 0]
第二個將選擇第三個元素。
使用double
索引時,將考慮索引指定的位置進行訪問。 相對於前面的示例,索引數組的double
版本將是:
[2 3]
一旦確定了索引(通過使用上述兩種方法之一),就可以使用它們來訪問不同數組的元素。
假設你有三個數組:
array
:您要查找要刪除的元素<= 1000
array
array_1
:第二個數組,要從中刪除與從array
刪除的元素位於相同位置的元素
array_11
:類似於array_1
這是使用兩種方法的示例:
% Identify the logical indexes of the element to be removed
logical_idx=array <= 1000;
% Identify the integer indexes of the element to be removed
double_idx=find(array <= 1000);
% Remove the unwanted elements by "direct" indexing
array(array <= 1000)=[]
% Remove unwanted elements using logical indexes
array_1(logical_idx)=[]
% Remove unwanted elements using integer indexes
array_11(double_idx)=[]
結束編輯
如果你想使用for
循環,你需要創建一個新數組並“反轉”“if”中的條件,以便識別必須存儲在新arrray中的原始數組元素(那些。 ..你不要貶低)。
array_2=[];
cnt=0;
for i=1:length(array)
if(array(i) > 1000)
cnt=cnt+1;
array_2(cnt)=array(i);
end
end
希望這可以幫助。
Qapla”
試試這個:
for i=1:1:size(array,1)*size(array,2)
if array(i)<=1000
array(i)=0;
end
end
array = nonzeros(array)
您可以使用以下代碼將代碼轉換為for循環。
for i=1:length(array)
some code here
end
但是,查看代碼,您可能希望將其重寫為矩陣運算。 看起來您的代碼正在刪除少於1000的任何內容,在這種情況下,您應該使用MATLABs數組索引功能來刪除這些值(請參閱下文)。
array(array<1000)=[];
該解決方案可能會更快,更容易理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.