Iterating through a dataset and creating a vector with according values
조회 수: 1 (최근 30일)
이전 댓글 표시
So I have a 10 000 X 1 vector (let's call it vector A) of different values ranging from -1 to 1. I want to create another 10 000 X 1 vector (let's call it vector B) that has values corresponding to the ones in the first vector. I want to create a loop that does this:
Everytime a value in vector A is bigger than 0.5, add the value 3 to vector B with the same corresponding position.
Everytime a value in vector A is smaller than -0.5, add the value 1 to vector B with the same corresponding position.
Everytime a value in vector A is between -0.5 and 0.5, add the value 2 to vector B with the same corresponding.
In that case, the resulting matrix should look like this:
[A] [B]
-0.9 1
-0.3 2
0.6 3
-0.2 2
-0.7 1
I know I need to use a loop but I struggle with this. Thank you so much for your help.
댓글 수: 2
Dyuman Joshi
2022년 9월 20일
What about border values i.e. 0.5 and -0.5, where value will you assign to corresponding B elements?
답변 (1개)
dpb
2022년 9월 20일
Rarely need loops for such things as this with MATLAB; either logical addressing or table lookup almost always comes to the rescue -- the latter (using the builtin interpolation routine) solution here would be
A=[-0.9;-0.3;0.6;-0.2;-0.7];
B=interp1([-1,-0.5,0.5,1],[1,2,3,3],A,'previous')
Alternatively, another lookup solution, with less overhead...
B=discretize(A,[-1,-0.5,0.5,1])
댓글 수: 4
Dyuman Joshi
2022년 9월 20일
After you get the values, you can get the values as such
str={'GT';'IN';'ST'};
A=[-0.9;-0.3;0.6;-0.2;-0.5;0.5];
B=interp1([-1,-0.5,0.5,1],[1,2,3,3],A,'previous');
%cell array
C=str(B)
%char array
D=cell2mat(C)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!