Given two vectors A,B - how can I create a vector v where v(n) = A(n):B(n)
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Christoph Michael Essler
am 11 Dez. 2016
Kommentiert: Christoph Michael Essler
am 11 Dez. 2016
Hello, and lots of thanks in advance to anyone that can help me out here! Now some more details about this question:
- A and B are of equal size.
- It doesn't matter (to me) whether v is a vector, cell array, or any other data type; whatever works will do.
Here an example:
A = [ 1 , 2 , 3 , 4 ]; B = [ 5 , 5 , 6 , 7] ==> C = [ (1,2,3,4,5), (2,3,4,5), (3,4,5,6), (4,5,6,7) ]
Why I'm asking: I tried implementing morphological operations myself, which all in all works, but performs very poorly, as the current version contains a double-for-loop. One instance of my functions would be the following:
function dilatedImage = ownDilate(binaryImage)
dilatedImage = binaryImage;
dilatedImage = dilatePoint(binaryImage,1:size(binaryArea,1)-1,1:size(binaryArea,2)-1);
end
function result = dilatePoint(binaryImage,py,px)
result = binaryImage;
x0 = max(1,px - 3);
y0 = max(1,py - 3);
x1 = min(size(binaryArea,2),px + 3);
y1 = min(size(binaryArea,1),py + 3);
%
dx0 = max(1,5-px);
dy0 = max(1,5-py);
dx1 = min(7,size(binaryArea,2) - px + 4);
dy1 = min(7,size(binaryArea,1) - py + 4);
%
for j = px
for i = py
se = structureElement(dy0(i):dy1(i),dx0(j):dx1(j));
if binaryArea(i,j)
result(y0(i):y1(i),x0(j):x1(j)) = or(se,result(y0(i):y1(i),x0(j):x1(j)));
end
end
end
end
Rather than using i,j in a for loop I would have liked to use py,px and without a for loop. Replacing the if statement would be easy I figure, I only need to create a vector of indices for which the if statement would apply and then use that for the assignment below. But what gives me headaches is the statement above that, since i cannot use the colon operator to create something as stated in the question. I know avoiding for statements isn't ALWAYS possible in Matlab, but I can't get rid of the feeling that it can in my case.
Anyways, thanks for your time, I hope I put everything detailed enough, but if I forgot something, please tell me!
0 Kommentare
Akzeptierte Antwort
Brendan Hamm
am 11 Dez. 2016
The function you are looking for is called arrayfun. This takes a function handle and n arrays and calls the function n-times, once for each element. Of course there is the potential in your example to have different sizes of data passed back so we set the UniformOutput flag to false.
A = [1,2,3,4];
B = [5,5,6,7];
f = @(a,b) a:b;
myData = arrayfun(f,A,B,'UniformOutput',false);
We can see the result is what you were looking for.
myData{1}
ans =
1 2 3 4 5
myData{2}
ans =
2 3 4 5
myData{3}
ans =
3 4 5 6
myData{4}
ans =
4 5 6 7
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!