How do I add values to a vector?
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Gabriel Aguirre
am 12 Dez. 2023
Kommentiert: Voss
am 12 Dez. 2023
How do I add values to a vector? I have the vector gdl_off = [1,2,14] and the vector X with 11 positions. I want the values in the positions specified by gdl_off to be 0, but if I use X(gdl_off,:) = 0, it only replaces the existing values.
gld_off = [1,2,14];
X = Kg_cut\F_cut;
X(gdl_off,:) = 0
but i have this
0
0
0.000248324742039762
-0.000614863156129983
0.000173205080756888
-0.000715692193816531
0.000207846096908266
-0.000735692193816530
9.80854194740139e-05
-0.000614863156129983
0.000346410161513776
0
0
0
and my original X is
0.000138564064605510
-0.000735692193816531
0.000248324742039762
-0.000614863156129983
0.000173205080756888
-0.000715692193816531
0.000207846096908266
-0.000735692193816530
9.80854194740139e-05
-0.000614863156129983
0.000346410161513776
1 Kommentar
jessupj
am 12 Dez. 2023
if you only want it to replace values, but NOT add new elements to the vector if you specify assignment to non-existing entries, then limit the assignment indices to the current length of the vector:
x( intersect(gld_off,1:numel(x)) ,:) = 0
otherwise, i'm not sure what you're after or what you're expecting.
Akzeptierte Antwort
Voss
am 12 Dez. 2023
If you want to insert a zero element at each of the locations specified by gld_off, in turn, you can do this:
X = [0.000138564064605510;-0.000735692193816531;0.000248324742039762;-0.000614863156129983;0.000173205080756888;-0.000715692193816531;0.000207846096908266;-0.000735692193816530;9.80854194740139e-05;-0.000614863156129983;0.000346410161513776];
gld_off = [1,2,14];
for ii = 1:numel(gld_off)
X = [X(1:gld_off(ii)-1); 0; X(gld_off(ii):end)];
end
disp(X)
However, the following is more efficient when you need to insert a large number of elements:
X = [0.000138564064605510;-0.000735692193816531;0.000248324742039762;-0.000614863156129983;0.000173205080756888;-0.000715692193816531;0.000207846096908266;-0.000735692193816530;9.80854194740139e-05;-0.000614863156129983;0.000346410161513776];
gld_off = [1,2,14];
NX_new = numel(X)+numel(gld_off);
X_new = zeros(NX_new,1);
X_new(setdiff(1:NX_new,gld_off)) = X;
X = X_new;
disp(X)
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!