Replace matrix elements with zero apart from specific vectors
3 views (last 30 days)
Show older comments
Hello,
I have 8 vectors, N1 to N8 which belong to a bigger matrix (2x28000). Four of the N-vectors are 1x3 and the other four are 1x41.
I want to replace the values of the big matrix with zeros apart from those belonging to the N-vectors.
I managed to extract the N-vectors from the bigger matrix using findNodes in PDE toolbox, e.g.:
'N1 = findNodes(model.Mesh,"region","Edge",1);'
But what I actually need is the whole bigger matrix with only the N-vectors values (and all the others =0) instead of just the N-vectors.
Hope it is clear.
Any idea on the method?
Thank you so much.
6 Comments
dpb
on 11 Jul 2023
But by what logic is one to know which elements to replace is the Q? still indeterminate. You can replace any value by any other; the problem is having a way to generate the indices of the locations to change programmatically.
I scanned through the whole conversation and don't see anywhere that is defined; you start out with something that is 2xN and some other vectors of some size that don't seem somehow related to that dimension and when @the cyclist asked for a smaller example that illustrated the issue, then your reply came back with something that is 4x4 but no associated vectors; just a set of points seemingly arbitrarily set to zero.
It's no wonder everybody is confused trying to keep up...
Accepted Answer
Voss
on 11 Jul 2023
N1 = [2 3 5];
N2 = [7 11 13];
N3 = [17 19 23 29];
x = [0 2 3 5; 7 11 13 6; 4 5 6 7; 17 19 23 29]
Rather than replacing unwanted elements of x with zero, you can think of it as starting with a matrix of all zeros the same size as x, and placing vectors into the matrix at the same locations they are in x.
% collect the vectors in a cell array:
C = {N1,N2,N3};
% get the length of each vector:
lenN = cellfun(@numel,C);
% get the total number of vectors:
nc = numel(C);
% make a new matrix, same size as x, initially all zeros:
[mm,nn] = size(x);
x_new = zeros(mm,nn);
% loop over rows of x:
for ii = 1:mm
% loop over vectors:
for jj = 1:nc
% find the locations where vector jj starts in row ii of x:
idx = strfind(x(ii,:),C{jj});
% place vector jj at those locations in row ii of x_new:
for kk = 1:numel(idx)
x_new(ii,idx(kk):idx(kk)+lenN(jj)-1) = C{jj};
end
end
end
% see the result:
x_new
6 Comments
Voss
on 18 Jul 2023
I won't have time to look at that today, so I recommend posting a new question about it. More people are likely to see a new question than a comment here anyway.
More Answers (0)
See Also
Categories
Find more on General PDEs in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!