How do I add values to a vector?

11 ビュー (過去 30 日間)
Gabriel Aguirre
Gabriel Aguirre 2023 年 12 月 12 日
コメント済み: Voss 2023 年 12 月 12 日
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 件のコメント
jessupj
jessupj 2023 年 12 月 12 日
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.

サインインしてコメントする。

採用された回答

Voss
Voss 2023 年 12 月 12 日
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
  2 件のコメント
Gabriel Aguirre
Gabriel Aguirre 2023 年 12 月 12 日
it worked, thank you
Voss
Voss 2023 年 12 月 12 日
You're welcome!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by