Reputation: 119
I am trying to write a function to replace a particular number of an array by the number of that position of another array. However, it does not allow me to do so. I am quite new in using MATLAB. Any help will be appreciated.
arr1 = [
1 3 8 9
2 47 10 4
2 4 6 86
6 8 11 4];
arr2 = [
3 4 1 8
8 2 99 1
0 6 77 11
9 3 2 1]
I want to write a function that will replace any particular number of arr1 with the number of arr2
of that index. Suppose I want to replace 2
from arr1
, then the output should be
out = [
1 3 8 9
8 47 10 4
0 4 6 86
6 8 11 4];
arr1(arr1==2) = arr2(arr1==2)
This allows me to do so. However, it does not allow me to write a generalizes function like
function new = arrayReplace(arr1,arr2,number)
idx = arr1==number;
new = (arr1(idx)=arr2(idx));
end
to replace any number of arr1
.
Any help!?
Upvotes: 1
Views: 51
Reputation: 38032
You're almost there:
function arr1 = arrayReplace(arr1,arr2,number)
idx = arr1==number;
arr1(idx) = arr2(idx);
end
or, perhaps less confusing:
function arr3 = arrayReplace(arr1, arr2, number)
idx = arr1==number;
arr3 = arr1;
arr3(idx) = arr2(idx);
end
Upvotes: 3