Clear Filters
Clear Filters

How do I add values to a vector?

2 views (last 30 days)
Gabriel Aguirre
Gabriel Aguirre on 12 Dec 2023
Commented: Voss on 12 Dec 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 Comment
jessupj
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.

Sign in to comment.

Accepted Answer

Voss
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)
1.0e-03 * 0 0 0.1386 -0.7357 0.2483 -0.6149 0.1732 -0.7157 0.2078 -0.7357 0.0981 -0.6149 0.3464 0
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)
1.0e-03 * 0 0 0.1386 -0.7357 0.2483 -0.6149 0.1732 -0.7157 0.2078 -0.7357 0.0981 -0.6149 0.3464 0

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!