필터 지우기
필터 지우기

normalize all but the zeros in a vector?

조회 수: 4 (최근 30일)
mark palmer
mark palmer 2023년 12월 24일
댓글: Walter Roberson 2023년 12월 24일
I have a vector that contains 0s, something like this [44 0 23 19 0 0 30]
and I want to normalize the non-0 elements to 1-10, for instance, but the 0s keep messing it up.
Is there a way (hopefully without using loops) to normalize while not affecting the 0s? In other words, take the values from 19-44 and convert them to stretch over 1-10.

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 12월 24일
편집: Dyuman Joshi 2023년 12월 24일
%Input
in = [44 0 23 19 0 0 30];
%Lazy preallocation, assuming all values are finite and not NaNs
out = 0*in;
%Indexing for non-zeros values
idx = in~=0;
%Output
out(idx) = rescale(in(idx), 1, 10)
out = 1×7
10.0000 0 2.4400 1.0000 0 0 4.9600
  댓글 수: 6
Dyuman Joshi
Dyuman Joshi 2023년 12월 24일
"But as soon as I say that, it will happen."
Haha, yes.
Mine used to be that too, but I am not sure how it changed into multiplying with 0. I think I'll go back to using zeros() soon, specially noting the difference in speed.
However, keeping performance in mind, maybe I should revisit this thread - https://in.mathworks.com/matlabcentral/answers/51411-initialize-a-mxn-matrix-with-the-same-number#answer_453549
Walter Roberson
Walter Roberson 2023년 12월 24일
y = zeros(size(x), 'like', x);
for extra robustness.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by