How can I rearrange the order of elements in a string given a matrix with positions?
2 次查看(过去 30 天)
显示 更早的评论
I have a string array of the form: str =["e1","e5", "e7", "e3"] %there are 16 e's in total
I want to take that str and order it such that I get a matrix of the form: M = [ e1 e5 e9 e13; e2 e6 e10 e14; e3 e7 e11 e15; e4 e8 e12 e16]
and then rearrange the matrix with the positions such that I get them ordered like in matrix l.
To do that I wrote:
for i=1:16
if ismember(sprintf('e%d',i), v)
Order(i) = sprintf('e%d',i);
else
Order(i)= sprintf('e%d',i);
end
[tf,loc] = ismember(sprintf('e%d',i),v);
Positions(i) = loc;
l = [1 5 2 6;...
9 13 10 14;...
3 7 4 8;...
11 15 12 16];
New_order = Positions(l);
In this example New_order = [1 2 0 0; 0 0 0 0; 4 3 0 0; 0 0 0 0]
Now, the problem is I have another vector b that is the same length as v: b = ( 1 5 7 3); and I want to create a matrix with its elements in the form of New_order, but if I try b(New_order) it won't allow me to do so because New_order contains zeros. How can I rearrange my vector b using New_order such that the output is: [1 5 0 0; 0 0 0 0; 3 7 0 0; 0 0 0 0] ?
0 个评论
回答(1 个)
Voss
2023-12-20
v = ["e1","e5","e7","e3"];
% these two lines replace your existing loop:
Order = compose("e%d",1:16);
[~,Positions] = ismember(Order,v);
l = [1 5 2 6;...
9 13 10 14;...
3 7 4 8;...
11 15 12 16];
New_order = Positions(l)
% now do the thing with b:
b = [1 5 7 3];
New_b = zeros(size(New_order));
idx = New_order ~= 0;
New_b(idx) = b(New_order(idx))
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!