How can I rearrange the order of elements in a string given a matrix with positions?

2 ビュー (過去 30 日間)
Keanu Guardiola Flores
Keanu Guardiola Flores 2018 年 2 月 5 日
回答済み: Voss 2023 年 12 月 20 日
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] ?

回答 (1 件)

Voss
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)
New_order = 4×4
1 2 0 0 0 0 0 0 4 3 0 0 0 0 0 0
% 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))
New_b = 4×4
1 5 0 0 0 0 0 0 3 7 0 0 0 0 0 0

カテゴリ

Help Center および File ExchangeGrid Lines, Tick Values, and Labels についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by