How to get variable data depending on the value from another column. In an Array

10 visualizaciones (últimos 30 días)
I have the following data,
Array =
[0.550 0.150
0.650 0.134
0.800 0.135]
how could I call on data from the second column depending on the value on the first column.
so if my code was
a = 5
b = 2
c = 3
while t < 50
t = 0
c = c + b * a * Q
M =
t = t + 1
end
If the value in the first colom were the values of M, and the second coloum were the values of Q how could I call the value of Q when M is equal to it.
I am trying to avoid an if and else if statement due to having many rows in my array
Please feel free to chnage the code to best show how I could do this. I am just looking for a simple demonstration of how I could archieve this not actually looking to solve the code above.

Respuestas (2)

Umar
Umar el 25 de Feb. de 2025

Hi @Michael,

After analyzing your code, you have a 2D array where the first column contains values representing `M` and the second column contains values representing `Q`. Your goal is to retrieve the corresponding value of `Q` when you have a specific value of `M`, while avoiding lengthy conditional statements. Below is a simple demonstration of how you can implement this in MATLAB. I will define the array, set up a loop, and use logical indexing to obtain the desired values without excessive conditional logic.

% Define the array with M and Q values
Array = [0.550, 0.150; 
       0.650, 0.134; 
       0.800, 0.135];
% Initialize parameters
 a = 5;
 b = 2;
 c = 3;
 t = 0;
% Loop to update c and calculate M
while t < 50
  % Assuming some calculation for Q based on c (you can adjust as needed)
  Q = c; % Placeholder for actual calculation of Q
    % Calculate M based on the given formula (example)
    M = Array(:,1); % Use the first column for M
    % Update c with a formula (this is just an example)
    c = c + b * a * Q;
    % Find Q corresponding to M using logical indexing
    % Let's assume we want to find Q when M equals some value.
    % Here we can use the last calculated M for demonstration.
    current_M = M(end); % Just an example; you can choose any specific value
    % Logical indexing to get Q corresponding to current_M
    index = Array(:,1) == current_M; 
    if any(index) % Check if there is any match
        corresponding_Q = Array(index, 2); % Get Q value(s) corresponding to M
        fprintf('For M = %.3f, corresponding Q = %.3f\n', current_M, 
        corresponding_Q);
      else
        fprintf('No corresponding Q found for M = %.3f\n', current_M);
    end
    t = t + 1; % Increment time
  end

So, in the above code

1. Array Definition: The `Array` variable holds your data where the first column represents `M` and the second column represents `Q`.

2. Parameter Initialization: Variables `a`, `b`, and `c` are initialized as per your requirements.

3. While Loop: The loop runs until `t` reaches 50, updating the value of `c` based on a placeholder calculation involving `Q`.

4. Finding Corresponding Q: The variable `current_M` is assigned from the last computed value of `M`. Logical indexing (`index`) checks which row in the first column matches current_M. If a match is found, it retrieves the corresponding value(s) from the second column (`Q`) and prints it.

5. Output: It displays the result directly in the console.

Here are some additional insights that I would like to share

This approach allows you to handle multiple rows efficiently without needing multiple conditional statements. If you need to handle cases where multiple matches may occur for different values of `M`, ensure that your indexing logic can accommodate that (e.g., using loops or additional logic as necessary). Also, you might consider using MATLAB's built-in functions like `find()` or logical arrays for more complex queries or larger datasets.

This solution is designed to be straightforward while allowing room for adaptation based on your specific needs in calculations or array manipulations.

Hope this helps.


Walter Roberson
Walter Roberson el 25 de Feb. de 2025
corresponding_values = Array(ismember(M, Array(:,1), 2));
However, the comparison between M and Array(:,1) that will be done is exact comparisons. If M is not extracted from Array(:,1) then chances are high that however M is calculated, it will not be bit-for-bit identical to the values in Array(:,1). Because of this you might consider using
corresponding_values = Array(ismembertol(M, Array(:,1), 2));
possibly together with optional parameters to ismembertol() to define the tolerance.
You might also consider using
interp1(Array(:,1), Array(:,2), M)
to interpolate M values into the array. Or possibly you might want
interp1(Array(:,1), Array(:,2), M, 'nearest')
or
interp1(Array(:,1), Array(:,2), M, 'next')
If you do use interp1() then you need to pay attention to the possibility that the input M is out of the range implied by Array(:,1) . The default return by interp1() in such a case is NaN, so you might want to enable extrapolation.
  2 comentarios
MIchael
MIchael el 25 de Feb. de 2025
Thankyou for the explanation thats great!
Would there be any simple code that would find the closest value of M the out put its respective Q value?
Walter Roberson
Walter Roberson el 25 de Feb. de 2025
interp1(Array(:,1), Q, M, 'nearest')
This compares M values to Array(:,1) and finds the nearest for each of the M values, and maps to the corresponding Q value.
In the case where M is scalar, then you can also use
[~, minidx] = min(abs(Array(:,1)-M));
Q(minidx)
or
[~, minidx] = min(Array(:,1)-M, ComparisonMethod="abs");
Q(minidx)

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by