簡體   English   中英

在Matlab中交換兩個向量的元素

[英]swapping two vector's elements in matlab

我有兩個向量v1 (1x9)v2 (1x4)

我必須編寫一個具有兩個輸入(x,y)out輸出的函數。

x應該是v1的索引號x

y應該是v2的索引號y

該函數應將v2xth元素替換為v1yth元素,並提供新的v2作為輸出。

舉個例子:

v1=[1 2 3 4 5 6 7 8 9];
v2=[1 2 3 4];
out = myfun(7,2);

那么輸出應該是

out = [1 7 3 4];

下次如果x=9並且y=1

out = myfun(9,1);
out = [9 7 3 4];

我的主要程序思想是

[MZ] = test(A,q)A是矩陣(mxn)q是長度mi = [1:m]; j = [1:n]的向量; C(:,J)= Q / A(:,J); 在c中找到最小元素。 例如,它是c(I,j),則x = I; 和y = j; gi = [1:x-1,x + 1:m]; j = [1:y-1,y + 1:n]; %開始新的計算語句…一種計算過程,用於找到矩陣M而不是A和向量Z而不是q。

程序結束

現在我想編寫我在該程序之前所做的myfunction

   elseif v(x) <= v1(n)  this program must working continuously (holding M and Z as new A and q in input and get the minimum ratio and so the new x and y ) until   v(x)==n break  

請幫忙

您可以save變量並將其load到下一個調用中。

function v2 = myfun(x,y)
v1=[1 2 3 4 5 6 7 8 9]; 
v2=[1 2 3 4];
if exist('v2.mat', 'file' ) ~= 0
   load('v2')
end
v2(y) = v1(x);
save('v2','v2');
end

您還可以使用persistant variable

function out = myfun(x,y)
persistent v
if isempty(v)
   v = [1 2 3 4];
end
v1=[1 2 3 4 5 6 7 8 9];
v(y) = v1(x);
out = v;
end

注意

mlock命令將當前正在運行的功能鎖定在內存中,以便隨后的清除功能不會將其刪除。 將函數鎖定在內存中還可以防止重新初始化文件中定義的任何持久變量。

編輯

從您的評論中得到了此表格,了解它的進展,

function out = test(x,y) 
persistent v 
if isempty(v) 
   v = [1 2 3 4]; 
end
v1 = [1 2 3 4 5 6 7 8 9];
v(y) = v1(x);
if x == 3;
   out = v;
   return 
elseif v(y) <= v1(9)
   statements 
end
out = v;
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM