Insert elements into vector

6 Ansichten (letzte 30 Tage)
NA
NA am 31 Okt. 2020
Bearbeitet: Stephen23 am 6 Nov. 2020
I have a vector 'index' and 'val_index'
index = [1;2;4;5;6;8;9];
index_val = [11;25;3;4;56;7;9];
I remove indices 3 and 7 from the 'index' . The 'removed_index' which I have is the cell array.
removed_index = {[7],[3]};
removed_val = {[1.1],[3.2]};
I want to insert removed indices and the values to the 'index'
Result should be:
index_all = [1;2;3;4;5;6;7;8;9];
index_val_all = [11;25;3.2;3;4;56;1.1;7;9];

Akzeptierte Antwort

Stephen23
Stephen23 am 31 Okt. 2020
index = [1;2;4;5;6;8;9];
index_val = [11;25;3;4;56;7;9];
removed_index = [7,3]; % simpler to use a numeric array
removed_val = [1.1,3.2]; % simpler to use a numeric array
Then all you need is:
idx = [index(:);removed_index(:)];
vec = [index_val(:);removed_val(:)];
vec(idx) = vec
idx(idx) = idx
  3 Kommentare
NA
NA am 6 Nov. 2020
Bearbeitet: NA am 6 Nov. 2020
If the 'index' is something like this:
index = [1;4;5;8;9];
index_val = [11;3;4;56;7];
removed_index = [7,3]; % simpler to use a numeric array
removed_val = [1.1,3.2]; % simpler to use a numeric array
If I use the above code,
idx = [index(:);removed_index(:)];
vec = [index_val(:);removed_val(:)];
vec(idx) = vec
idx(idx) = idx
I got this result
idx =[1;4;3;4;5;7;7;8;9]
vec =[11;3;3.2;3;4;1.1;1.1;56;7];
How can I get this result
idx =[1;3;4;5;7;8;9]
vec = [11;3.2;3;4;1.1;56;7]
Stephen23
Stephen23 am 6 Nov. 2020
Bearbeitet: Stephen23 am 6 Nov. 2020
index = [1;4;5;8;9];
index_val = [11;3;4;56;7];
removed_index = [7,3]; % simpler to use a numeric array
removed_val = [1.1,3.2]; % simpler to use a numeric array
idx = [index(:);removed_index(:)];
vec = [index_val(:);removed_val(:)];
[idx,ids] = sort(idx); idx
idx = 7×1
1 3 4 5 7 8 9
vec = vec(ids)
vec = 7×1
11.0000 3.2000 3.0000 4.0000 1.1000 56.0000 7.0000

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by