combine for loop and ~isinf,but there is an error in every loops except the result in the first loop

1 次查看(过去 30 天)
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?

采纳的回答

Stephen23
Stephen23 2019-3-29
编辑:Stephen23 2019-3-29
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 个评论
yang-En Hsiao
yang-En Hsiao 2019-3-29
you mean like this ?
v = [3,6,1,Inf ];
z=nan(1,length(k))
for k = 1:length(v)
n = v(k)
z(k) = n(~isinf(n ))
end
meann=mean(z(~isinf(z )))
but the error show to me
In an assignment A(I) = B, the number of
elements in B and I must be the same.
Error in Untitled2 (line 6)
z(k) = n(~isinf(n ))
Stephen23
Stephen23 2019-3-30
编辑:Stephen23 2019-3-30
"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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by