How to run a for loop when variables are different lengths?

Here I have outlined two variables, delta and phi. I want to calculate beta for every possible combination of phi and delta but am not sure how since they are different lengths.
delta = -23.28:0.01:23.28;
phi = -90:1:90;
beta = phi - delta;

 Accepted Answer

The easiest way is to make one into a column vector and keep one as a row vector. This creates a matrix for ‘beta’:
delta = -23.28:0.01:23.28;
phi = -90:1:90;
beta = phi - delta(:);
If your release/version is R2016a or earlier:
beta1 = bsxfun(@minus, phi, delta(:));
Those both produce the same result.

More Answers (2)

You can do it vectorized using meshgrid(). Try this:
delta = -23.28:0.01:23.28;
phi = -90:1:90;
[deltaAll, phiAll] = meshgrid(delta, phi);
beta = phiAll - deltaAll;
imshow(beta, [], 'XData', delta, 'YData', phi);
colormap(jet(256));
colorbar;
axis('on', 'image');
xlabel('delta', 'FontSize', 24);
ylabel('phi', 'FontSize', 24);
Hi,
Here is the solution to your exercise:
delta = -23.28:0.01:23.28;
phi = -90:1:90;
for ii = 1:numel(delta)
for jj=1:numel(phi)
beta(ii,jj) = phi(jj) - delta(ii);
end
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

SW
on 7 Sep 2020

Edited:

on 7 Sep 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!