Changing numbers in dataset

조회 수: 1 (최근 30일)
Rajesh
Rajesh 2022년 6월 7일
댓글: Voss 2022년 6월 8일
Hi,
I have a dataset of size m*n. The dataset only contains integer numbers between 1 to 5. Now I want to change the numbers as
1=-1
2=-1+(2/4)=-1/2
3=-1+(4/4)=0
4=-1+(64)=1/2
5=-1+(8/4)=1
Is there any efficient way of doing that?

채택된 답변

Voss
Voss 2022년 6월 7일
편집: Voss 2022년 6월 7일
Considering that -1 can be written as -1+(0/4), a pattern becomes clear:
1 -> -1+(0/4)
2 -> -1+(2/4)
3 -> -1+(4/4)
4 -> -1+(6/4)
5 -> -1+(8/4)
In general, say:
x -> -1+(y/4)
The pattern is that each time x is incremented by 1 on the left-hand side: x = (1, 2, 3, 4, 5), that corresponds to y being incremented by 2 on the right-hand side: y = (0, 2, 4, 6, 8). And y is 0 when x is 1.
Thus we can say that y = 2*(x-1), so that the rule is:
x -> -1+(2*(x-1)/4)
or, simplifying:
x -> -1+(x-1)/2
So if x is your m-by-n matrix, then the transformed version of x is -1+(x-1)/2.
m = 3;
n = 4;
x = randi(5,[m,n])
x = 3×4
4 2 5 2 3 2 1 2 1 5 5 2
new_x = -1+(x-1)/2
new_x = 3×4
0.5000 -0.5000 1.0000 -0.5000 0 -0.5000 -1.0000 -0.5000 -1.0000 1.0000 1.0000 -0.5000
  댓글 수: 2
Rajesh
Rajesh 2022년 6월 7일
편집: Rajesh 2022년 6월 7일
Thank you very much!
Voss
Voss 2022년 6월 8일
You're welcome!

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

추가 답변 (1개)

Chris
Chris 2022년 6월 7일
For only five values, I think it's pretty efficient to do a direct replacement:
ds_new = zeros(size(dataset))
ds_new(dataset == 1) = -1;
ds_new(dataset == 2) = -0.5;
% ...etc
If you need more flexibility, this is what I came up with:
ds = randi(5,4)
ds = 4×4
4 4 1 2 4 2 5 4 3 1 2 5 1 3 2 3
ints = 1:5;
vals = 0.5*(ints-1)-1;
dsnew = zeros(size(ds));
for idx = 1:numel(ints)
dsnew(ds == idx) = vals(idx);
end
dsnew
dsnew = 4×4
0.5000 0.5000 -1.0000 -0.5000 0.5000 -0.5000 1.0000 0.5000 0 -1.0000 -0.5000 1.0000 -1.0000 0 -0.5000 0

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by