To be clear, I'm changing my question as follows with more details:
——
Here is the code segment I'm working on:
NphaseSteps = 4; % Assume that TM is a 10x10 random matrix that includes both real and complex numbers.
% But it is fixed after created randomly.
TMsize = length(TM);focusX = 5; focusY = 5;function inFieldA = WSfunction(NphaseSteps, TM, TMsize, focusX, focusY)% This function is supposed to return inFieldA that gives 1) the maximum value
% at the target position (focusX,focusY) inside the outField matrix 2) the
% optimized outField such that all other elements other than (focusX,focusY)
% inside outField have "at most" half of the target position value.
ticfprintf('The number of possible random matrices: %s \n',NphaseSteps^(TMsize^2));phases = exp( 2*pi*1i * (0:(NphaseSteps-1))/NphaseSteps );nIterations = 5;inField = cell(1,nIterations);i = 1; j = 0;while i <= nIterations %number of iterations
ind = randi([1 NphaseSteps],TMsize,TMsize); inField{i} = phases(ind); j = j+1; outField{i} = TM * inField{i}; outI = abs(outField{i}).^2; targetIafter(i) = abs(outField{i}(focusX,focusY)).^2; middleI = targetIafter(i) / 2; if max(max(outI)) == targetIafter(i) outI(focusX,focusY)=0; if (outI > middleI) == zeros(TMsize,TMsize) i = i + 1; end end if mod(j,10^6) == 0 fprintf('The number of random matrices tried: %d million \n',j/10^6) end endfprintf('The number of random matrices tried in total: %d \n',j)[maxInt, maxInd] = max(targetIafter);inFieldA = inField(maxInd);tocend
This program basically creates a 10×10 random input matrix inField that only includes 4 elements (number of phase steps) and multiplies it with a 10×10 fixed matrix TM to obtain a 10×10 output matrix outField. Now, I want to fix two things about the program:
- Since the inField matrices are created randomly, the program will create equal matrices many times. I want to eliminate the equal inField matrices before they go into the "if statement". For this I need to change the cellfun part but I don't know how to do it in the most efficient way.
- In the outField matrix I want a specific matrix element to have the largest value. First part of the "if statement" deals with that. But, I additionally want the other elements (other than my target matrix element) to have values smaller than the half of the target value. In the second part of the "if statement" I wanted to handle this situation but I think it's too complicated and not very efficient. Can you offer a better way to do it?
Best Answer