How do I add values to a vector?
2 views (last 30 days)
Show older comments
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 Comment
jessupj
on 12 Dec 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.
Accepted Answer
Voss
on 12 Dec 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)
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!