필터 지우기
필터 지우기

How do I add values to a vector?

조회 수: 2 (최근 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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by