What changes are needed in the code?

i want to swaps characters of s as specified by the indices present in the pairs variable. pairs is a 2-column matrix, where on each row, i have given the positions of the two characters that need to swap. eg s = orange & pairs = [1 2]. out expected is roange. what changes you recommend in this code.
function [arr] = shuffletext ( pairs, s)
a = 0;
b = 0;
for i = 1:numel(s)
for j = pairs
s(i) = a;
a = b;
b = s(i);
end
end
arr = b;
Still its not showing any output just a blank if i call the function
using: disp( shuffletext( [1 2], 'orange') )
Output
>> disp( shuffletext( [1 2], 'orange') )
>>

Antworten (1)

Cris LaPierre
Cris LaPierre am 11 Nov. 2021

0 Stimmen

p = [1 2];
s = 'orange';
s(p) = s(fliplr(p))
s = 'roange'

6 Kommentare

Manav Divekar
Manav Divekar am 11 Nov. 2021
I know this function but want to see if for loop also works or not, you can help me with for loop that would be great.
Cris LaPierre
Cris LaPierre am 11 Nov. 2021
If you know the indices, I don't see why you need for loops.
Manav Divekar
Manav Divekar am 11 Nov. 2021
if there is a matrix like [1 2; 4 2] then output expected for orange in first row is roange and the for second row will be rnaoge, the itreration is required. Thats the reason i there is need of for loop.
Cris LaPierre
Cris LaPierre am 11 Nov. 2021
That explains the outer loop, but not the inner one.
There is no 'swap' feature. You need to
  1. copy the first letter to a temporary variable
  2. replace the first letter in s with the second letter
  3. Replace the second letter in s with the letter dopied in step 1
function [arr] = shuffletext ( pairs, s)
a = 0;
b = 0;
for i = 1:numel(s)
for j = pairs
s(i) = a;
a = b;
b = s(i);
end
end
arr = b;
Still its not showing any output just a blank if i call the function
using: disp( shuffletext( [1 2], 'orange') )
Output
>> disp( shuffletext( [1 2], 'orange') )
>>
Cris LaPierre
Cris LaPierre am 12 Nov. 2021
Bearbeitet: Cris LaPierre am 12 Nov. 2021
I strongly recommend going through MATLAB Onramp. It will help give you an good understanding of the fundamentals of MATLAB.
Again, do don't need the second for loop because you are not using j anywhere.
Also, assignment (equals sign) places what is on the right into what is on the left. So s(i) = a will take the value assigned to a, which is 0, and place it in the ith position of s. This assignment is likely not doing what you expect since s is a character array and a is a double.
a=0;
s='orange';
s(2) = a
s = 'o ange'

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2021a

Tags

Gefragt:

am 11 Nov. 2021

Bearbeitet:

am 12 Nov. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by