问题描述
我有一个可变大小为零的Matlab数组,以及一个单元格数组中的字符列表。
单元格数组:
{'0000'}
{'0011'}
我想在数组中每0位放置-1,并在1位放置1。
示例:
-1 -1 -1 -1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 -1 -1 -1 -1 0 0 0 0 0 0 0 0
....
0 0 0 0 0 0 0 0 0 0 0 0 -1 -1 -1 -1
-1 -1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
...
0 0 0 0 0 0 0 0 0 0 0 0 -1 -1 1 1
如您所见,基于单元格数组{0000}
的前四个输出行将这4个转换后的位完全放在所有输出行中。第二个字符{0011}
相同。在这种情况下,数组大小为(8 x 16)。 -1 -1 -1 -1
在数组中从左向右传播的次数也是可变的,在这种情况下,最多为4列4位。
以相同的方式,例如,如果有5位:
单元格数组:
{'00000'}
{'00111'}
这将是数组:
-1 -1 -1 -1 -1 0 0 0 0 0
0 0 0 0 0 -1 -1 -1 -1 -1
-1 -1 1 1 1 0 0 0 0 0
0 0 0 0 0 -1 -1 1 1 1
在这种情况下,数组-1 -1 -1 -1 -1
从左向右传播的次数最多为2列5位,因此数组大小为(4 x 10)。
第一个示例进行4次传播,第二个示例仅进行2次传播,因为可用列号也是一个变量。这是一个单独的参数。
这是我的代码不起作用:
counterop=0
counter=1
for i=1: numel(listofss) % list of ss is the list of charecters (my examples has 3)
for c = 1:1:(ss) % row
for e = counter:counter+(n-1) % column
A_ss(c,e)= -1 %A_ss is the predefined matrix (in my example a 12 by 64 matrix )
end
counter=counter + n
counterop=counterop+1
end
end
if counterop > n-1
counter = 1
counterop=1
end
最好带有for循环的工作代码。
解决方法
以下是使用kron
的示例:
np = 4; % number of permutations/repetitions
nc = 2; % number of cells
x = {'0000','0011'} % the cell
M = sign(cell2mat(x.')-48.5) % convert string to number: ['01'] -> [-1 1]
M = kron([eye(np)],M) % apply the kronecker tensor product
ind = reshape(1:nc*np,nc,np).'; % create an alternated index
M(ind(:),:) % index the matrix
对于转换,我使用了一个小技巧:在matlab中使用'0'- 0 = 48
,因为matlab允许隐式转换。因此,matlab将字符“ 0”的相应ascii值设为48。
结果:
M =
-1 -1 -1 -1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 -1 -1 -1 -1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 -1 -1 -1 -1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 -1 -1 -1 -1
-1 -1 1 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 -1 -1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 -1 -1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 -1 -1 1 1
要了解此答案的工作原理,您必须阅读一些有关以下内容的文档:kron
,cell2mat
,implicit casting,
matrix indexing,以及有关transpose operator .'