我在matlab中有一个调查数据,我有一些反向编码的项目。我只需要在某些问题中进行反向编码。我正在使用这段代码reversecoding = myStruct.mysurvey(:,4) == 5 ;
mySturct.mysurvey(reversecoding,4) = 3 ;
但我意识到使用它可能会遇到一些问题。
例如,当我重新编码3到5的值时;
myStruct.mysurvey=
3 3 3 3
6 6 6 6
3 3 3 3
7 6 6 7
4 3 5 5 <--
5 5 4 5 <--
...
reversecoding = myStruct.mysurvey(:,4) == 5 ;
mySturct.mysurvey(reversecoding,4) = 3
%after (the last 2 values has recoded to 3)
myStruct.mysurvey=
3 3 3 3
6 6 6 6
3 3 3 3
7 6 6 7
4 3 5 3 <--
5 5 4 3 <--
...
但在那之后,当我重新编码3到5时,它将我的所有3个(包括我刚从5中重新编码的那个)重新编码为5个。
举例说明;
%after I recode 3s to 5
myStruct.mysurvey=
3 3 3 3
6 6 6 6
3 3 3 3
7 6 6 7
4 3 5 3 <--
5 5 4 3 <--
...
reversecoding = myStruct.mysurvey(:,4) == 3 ;
mySturct.mysurvey(reversecoding,4) = 5 ;
myStruct.mysurvey = 3 3 3 5 6 6 6 6 3 3 3 5 7 6 6 7 4 3 5 5&lt; - 5 5 4 5 < - %他们又是5 ... 再次%,第4列的最后两个值返回到5 ...
如何摆脱这个问题?这是代码;
reversecoding = myStruct.mysurvey(:,4) == 5 ;
mySturct.mysurvey(reversecoding,4) = 3 ;
% after
reversecoding = myStruct.mysurvey(:,4) == 3 ;
mySturct.mysurvey(reversecoding,4) = 5 ;
% all other values will be transformed.
%old 1 will be 7
%old 2 will be 6
...
%old 6 will be 2
%old 7 will be 1
重新编码它们的最佳方法是什么?我将从1到7重新编码。
答案 0 :(得分:1)
您可以使用container map创建从旧值到新值的映射。这很简单:
map = containers.Map(old_values, new_values);
或在你的情况下
map = containers.Map(1:10, 10:-1:1);
然后,您可以使用map
将旧值映射到相应的新值,如下所示:
>> map(1)
ans =
10
>> map(4)
ans =
7
请注意,您只能在单个值上“调用”map
,而不能在数组上调用arrayfun
。但你可以使用例如>> myStruct.mysurvey(:, 4) = [9, 2, 1, 10, 4]; % Example data
>> myStruct.mysurvey(:, 4)
ans =
9
2
1
10
4
>> myStruct.mysurvey(:, 4) = arrayfun(@(x) map(x), myStruct.mysurvey(:, 4));
>> myStruct.mysurvey(:, 4)
ans =
2
9
10
1
7
将此简化为一次调用:
class ChangeableType<T>(private var value: T, private val onChange: () -> Unit) {
fun set(value: T) {
this.value = value
this.onChange.invoke()
}
}
class MyRandomClass() {
val something = ChangeableType(0, { System.print("Something new value: $value") })
val anotherThing = ChangeableType("String", { System.print("Another thing new value: $value") })
}
class ConsumingClass {
val myRandomClass = MyRandomClass()
fun update() {
myRandomClass.apply {
something.set(1)
anotherThing.set("Hello World")
}
}
}
答案 1 :(得分:0)
我找到了解决这个问题的另一种方法,但这有点像颈部疼痛。
我使用逻辑索引为每个值创建了不同的变量。
%find elements to recode
fiveto3 = myStruct.mySurvey(:,4) == 5 ;
threeto5 = myStruct.mySurvey(:,4) == 3 ;
...
twoto6= myStruct.mySurvey(:,4)== 2;
sixto2= myStruct.mySurvey(:,4)== 6;
...
oneto7= myStruct.mySurvey(:,4) == 1;
sevento1 = myStruct.mySurvey(:,4)==7;
% time to recode
myStruct.mySurvey(fiveto3 , 4) = 3 ;
myStruct.mySurvey(threeto5,4) = 5 ;
myStruct.mySurvey(twoto6 , 4) = 6 ;
myStruct.mySurvey(sixto2 , 4) = 2 ;
myStruct.mySurvey(oneto7 , 4) = 7 ;
myStruct.mySurvey(sevento1 , 4) = 1 ;
clear fiveto3 threeto5 twoto6 sixto2 oneto7 sevento1 % to get rid of these variables.
这也有效但如果要重新编码的值超过10个,则需要更多的努力和更多的行。您可以尝试容器地图或这个!