Creat a matrix based off an if statement

I am trying to make a look and when IFIX(J,K) == 0 I want the certain column from Global_K to populate displacement. However, each time i run the if statement it rewrites over the same column. I want it to add a new column each time. Please help!
if IFIX(J,K) == 0
for L = 1:(NJ*NDJ)
displacement(L) = Global_K(L,NRC);
end
end
else
for L = 1:(NJ*NDJ)
Global_K(L,NRC) = 0;
end
end

4 Comments

I can't see the rest of your code so I don't know what's happening, but if NJ and NDJ aren't changing in your code then neither is L. It would execute like this:
  1. If IFIX(J,K) == 0
  2. displacement(1) = Global_K(1,NRC)
  3. displacement(2) = Global_K(2,NRC)
  4. And so on
  5. End "IF", return to code
Your code should be overwriting the values in displacement each time as it's written.
Correct NJ and NDJ aren't changing. Basically I want the number of columns in the displacement to equal number of times the code runs through the if statement. Perhaps, I should share more of the code
for J = 1:NJ
for K = 1:NDJ
NRC = (J-1)*NDJ +K;
if IFIX(J,K) == 0
for L = 1:(NJ*NDJ)
displacement(L) = Global_K(L,NRC);
end
else
for L = 1:(NJ*NDJ)
Global_K(L,NRC) = 0;
end
end
end
end
Currently, displacement will only ever be a vector of length NJ*NDJ. If you want multiple columns, you have to add them. A tip: to add a column to an existing matrix, perform the following:
matrix = [];
vector = 1:10;
matrix = [matrix; vector];
matrix = [matrix; vector];
disp(matrix);
Adjust that so it does what you want (this concatenates a row vector to the bottom of the matrix).
No this didn't do what I wanted to do.

Answers (1)

Hi,
From the functionality of the code I see a better way to write the code. Here I see array indexing can be used to avoid lot of for loops. Hope the below code achieves what is required.
% For experiment assuming values of NJ and NDJ
NJ = 5;
NDJ = 4;
Global_K = randi([1 100],[NJ*NDJ,NJ*NDJ]);
IFIX = randi([0 2],[NJ,NDJ]);
% Actual Logic
condition = IFIX==0;
% For flattening the matrix to get row-wise NRC
conditionTranspose = condition.';
% Final Indices of Global_K to add to displacement
conditionFinal = conditionTranspose(:);
displacement = Global_K(:,conditionFinal);
Global_K(:,conditionFinal) = 0;

This question is closed.

Tags

Asked:

on 23 Apr 2020

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!