How to replace zeros in a matrix by elements of an array in Matlab?

Click For Summary
SUMMARY

The discussion focuses on replacing zeros in a matrix with elements from an array in MATLAB. The matrix ID, initially containing zeros and ones, is transformed such that all ones are replaced with zeros, and zeros are replaced with elements from the array EA, which is defined as EA=1:8. The final output matrix ID is structured to reflect these changes, demonstrating effective use of nested loops and indexing in MATLAB.

PREREQUISITES
  • Understanding of MATLAB syntax and operations
  • Familiarity with matrix manipulation in MATLAB
  • Knowledge of indexing and loops in programming
  • Basic concepts of arrays in MATLAB
NEXT STEPS
  • Explore MATLAB's array indexing techniques
  • Learn about nested loops in MATLAB for matrix operations
  • Investigate MATLAB functions for conditional replacements in arrays
  • Study MATLAB's built-in functions for matrix manipulation
USEFUL FOR

This discussion is beneficial for MATLAB users, students working on matrix operations, and anyone looking to enhance their programming skills in array manipulation within MATLAB.

quetzal
Messages
5
Reaction score
0

Homework Statement


I have a matrix that contains zeros but it may contain also ones. For example:
Code:
                   ID=[1 0 0 0;
                       0 0 0 0;
                       1 0 1 1]
I'm trying to replace all the ones by zeros and all the zeros by elements of an array EA going column-wise so that the resulting matrix ID would look like:
Code:
EA=1:8;        ID=[0 2 5 7;
                   1 3 6 8;
                   0 4 0 0]

Homework Equations


The Attempt at a Solution


I tried it this way but don't know how to finish it:
Code:
D=3;
N=4;
ID=zeros(D,N);
equations=sum(ID(:)==0);% number of zeros in matrix ID
EA=1:equations;

for j=1:N
    for i=1:D
        if ID(i,j)==1
           ID(i,j)=0;
        else            
           ID(i,j)=?;           
        end
    end
end
 
Last edited:
Physics news on Phys.org
you could make a separate variable say num for EA and do this
num=1;

for j=1:N
for i=1:D
if ID(i,j)==1
ID(i,j)=0;
else
ID(i,j)=EA(1,num);
num+=1;
end
end
end
 
Awesome! I've got it done similarly...Thanks!
num=1;

Code:
for j=1:N
for i=1:D
if ID(i,j)==1
ID(i,j)=0;
else
ID(i,j)=EA(num);
num=num+1;
end
end
end
 

Similar threads

  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
43
Views
5K
  • · Replies 18 ·
Replies
18
Views
2K
Replies
2
Views
1K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
Replies
7
Views
3K