combine for loop and ~isinf,but there is an error in every loops except the result in the first loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
yang-En Hsiao
le 29 Mar 2019
Modifié(e) : Stephen23
le 30 Mar 2019
I use ~isinf and a for loop to make a code,in this code ,i want to let the un-Inf value to show me in each loop,however,i found that there is a error here,but i can't find where do i wrong
c=[ 3 6 1 Inf]
fg=c(~isinf(c))
for k=1:4
ad=c(~isinf(c(k)))
end
So in fact ad should show me as the same as each element in fg,like this
fg = 3 6 1
ad = 3
ad = 6
ad = 1
ad = []<-----maybe won't be shown
However,the window show me
fg = 3 6 1
ad = 3
ad = 3
ad = 3
ad = []<-----maybe won't be shown
Where i am wrong with the code?
0 commentaires
Réponse acceptée
Stephen23
le 29 Mar 2019
Modifié(e) : Stephen23
le 29 Mar 2019
v = [3,6,1,Inf];
for k = 1:numel(v)
n = v(k);
z = n(~isinf(n))
end
displays:
z = 3
z = 6
z = 1
z = []
"i can't find where do i wrong"
Your code uses a scalar logical index:
~isinf(c(k))
Logical indexing is positional (it is not like subscript or linear indexing), so when you use a scalar logical index it acts only on the first element of the array, i.e. you either select the first element or you do not. That is exactly what your example output shows.
You cannot use a scalar logical index to work like a subscript and also expect it to select different elements of an array (i.e. not the first element). For that you would need to create a non-scalar logical index (normally these are the same size as the array being indexed) or use subscript/linear indexing first (which is what my answer does).
7 commentaires
Stephen23
le 30 Mar 2019
Modifié(e) : Stephen23
le 30 Mar 2019
"you mean like this ?"
No. You told us that you generate "the result from every loop", so that is what my code requires.
Also your length(k) does not make much sense for array preallocation, because k is a scalar.
You should do something like this:
v = [3,6,1,Inf];
N = numel(v); % or however you define the number of loops.
y = nan(1,N); % preallocate!
for k = 1:N
y(k) = v(k); % your value (calculated...)
end
m = mean(y(~isinf(y)))
Where, clearly, in your actual code you generate that value, rather than selecting elements of the vector v like we are using here for these examples.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!